Search code examples
c#pinvokeintptr

How is IntPtr Marshalled?


Until recently I thought that marshalling an IntPtr in P/Invoke would just involve a 'blitting' operation; i.e. simply copying the pointer from e.g. C++ to C#.

However I was talking to someone recently that mentioned there was more to it than that. He specifically mentioned that the IntPtr marshalling takes in to account byte order (i.e. little-endian or big-endian). That seems strange to me though: Surely the byte order wouldn't matter unless we were sending the pointer over to another machine, and god knows why you'd do that?

Can anyone here shed a little more light on this for me; and possibly link to some resource for further reading? Thank you.


Solution

  • It's a straight blit, no different conceptually from int or long. Obviously it's 4 bytes under x86, and 8 bytes under x64. There's no magic here.

    Endianness is never an issue with p/invoke marshalling. The endianness is a property of the underlying machine. The unmanaged DLL that you call using p/invoke using the same endianness as your managed code, because they run on the same machine.