fork(3) download
  1. using System;
  2. using System.Diagnostics;
  3. using System.Runtime.InteropServices;
  4. using System.Text;
  5.  
  6. public class Test
  7. {
  8. [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi, Size = 24)]
  9. struct Valid
  10. {
  11. public uint Length;
  12. public uint Version;
  13. [MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)]
  14. public byte[] MachineId;
  15. }
  16.  
  17. [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi, Size = 24)]
  18. struct Invalid
  19. {
  20. public uint Length;
  21. public uint Version;
  22. [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 16)] public string MachineId;
  23. }
  24.  
  25. public static void Main()
  26. {
  27. var bytes = new byte[]
  28. {
  29. 0x58, 0, 0, 0,
  30. 0, 0, 0, 0,
  31. 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4A, 0x4B, 0x4C, 0x4D, 0x4E, 0x4F, 0
  32. };
  33.  
  34. var pinnedBuffer = GCHandle.Alloc(bytes, GCHandleType.Pinned);
  35. var ptr = pinnedBuffer.AddrOfPinnedObject();
  36.  
  37. // Works!
  38. Debug.Assert(bytes.Length == Marshal.SizeOf<Valid>());
  39.  
  40. var trackerData1 = Marshal.PtrToStructure<Valid>(ptr);
  41.  
  42. Console.WriteLine("Length: {0}", trackerData1.Length);
  43. Console.WriteLine("Version: {0}", trackerData1.Version);
  44. Console.WriteLine("MachineId: {0}", Encoding.ASCII.GetString(trackerData1.MachineId));
  45.  
  46. // Doesnt work!
  47. Debug.Assert(bytes.Length == Marshal.SizeOf<Invalid>());
  48.  
  49. // Throws System.AccessViolationException
  50. var trackerData2 = Marshal.PtrToStructure<Invalid>(ptr);
  51.  
  52. Console.WriteLine("Length: {0}", trackerData2.Length);
  53. Console.WriteLine("Version: {0}", trackerData2.Version);
  54. Console.WriteLine("MachineId: {0}", trackerData2.MachineId);
  55.  
  56. pinnedBuffer.Free();
  57.  
  58. Console.In.ReadLine();
  59. }
  60. }
Success #stdin #stdout 0.01s 29664KB
stdin
Standard input is empty
stdout
Length: 88
Version: 0
MachineId: ABCDEFGHIJKLMNO
Length: 88
Version: 0
MachineId: ABCDEFGHIJKLMNO