-1

I'm trying to serialize my struct and I need to convert IntPtr to byte array. Here's an example:

//IntPtr hWnd = this.Handle;    

int size = Marshal.SizeOf(typeof(IntPtr));
byte[] managedArray = new byte[size];
Marshal.Copy(hWnd, managedArray, 0, size);  //Exception: AccessViolationException

Why?

c00000fd
  • 20,994
  • 29
  • 177
  • 400
  • This will try to interpret hWnd as a pointer to an (unmanaged) memory location. If hWnd is in fact a window handle (as the name suggests), it will obviously not work. – Klaus Gütter Jul 07 '22 at 14:17
  • "serialize my struct and I need to convert IntPtr to byte array", Whatever it is you are doing is probably the wrong thing, please show the rest of the `struct` code – Charlieface Jul 07 '22 at 15:39

1 Answers1

0

The handle to a window (hWnd) isn't a pointer to valid memory, it's an index into the internal data structures of Windows.

If you want to split the number itself into bytes in one of the worst ways possible however, try this instead:

Marshal.Copy(&hWnd, managedArray, 0, size);  
Blindy
  • 65,249
  • 10
  • 91
  • 131