Advertisement
FrayxRulez

Untitled

Mar 26th, 2015
361
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.69 KB | None | 0 0
  1. internal static T GetStruct<T>(byte[] structure)
  2. {
  3. int num = Marshal.SizeOf(typeof(T));
  4. using (DisposableGCHandle disposableGCHandle = DisposableGCHandle.Alloc(structure, GCHandleType.Pinned))
  5. {
  6. IntPtr intPtr = IntPtr.Add(disposableGCHandle.AddrOfPinnedObject(), 0);
  7.  
  8. return (T)Marshal.PtrToStructure(intPtr, typeof(T));
  9. }
  10. }
  11.  
  12.  
  13. public sealed class DisposableGCHandle : IDisposable
  14. {
  15. private GCHandle handle;
  16.  
  17. public bool IsAllocated
  18. {
  19. get
  20. {
  21. return this.handle.IsAllocated;
  22. }
  23. }
  24.  
  25. public object Target
  26. {
  27. get
  28. {
  29. return this.handle.Target;
  30. }
  31. }
  32.  
  33. public DisposableGCHandle()
  34. {
  35. }
  36.  
  37. public IntPtr AddrOfPinnedObject()
  38. {
  39. return this.handle.AddrOfPinnedObject();
  40. }
  41.  
  42. public static DisposableGCHandle Alloc(object target, GCHandleType handleType = GCHandleType.Normal)
  43. {
  44. if (target == null)
  45. {
  46. throw new ArgumentNullException("target");
  47. }
  48. DisposableGCHandle disposableGCHandle = new DisposableGCHandle()
  49. {
  50. handle = GCHandle.Alloc(target, handleType)
  51. };
  52. return disposableGCHandle;
  53. }
  54.  
  55. public void Dispose()
  56. {
  57. if (this.IsAllocated)
  58. {
  59. this.Free();
  60. }
  61. }
  62.  
  63. public void Free()
  64. {
  65. this.handle.Free();
  66. }
  67. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement