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?
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: