Search code examples
c#intptr

Is it necessary to utilize the IntPtr constructor to set an IntPtr to equal another IntPtr?


I am currently refactoring an application to 64 bit and I am trying to understand a specific use of the IntPtr. The code that I am trying to understand is in the form of:

IntPtr a = Marshal.AllocHGlobal(SomeObjectSize); //SomeObjectSize is calculated based on some standard
IntPtr b = IntPtr(a.ToInt32());

Now at first blush I figured I could just change a.ToInt32() to a.ToInt64(), which worked for instances where an int needed to go into an IntPtr, but since a and b are both IntPtr types, couldn't I just use IntPtr b = a; since IntPtr is a value type? I figure this will keep me from having to check for 64 bit or 32 bit builds in this kind of situation and the MSDN docs don't seem to imply any magic in the IntPtr constructor.

Basically my question is why would I use

IntPtr a = Marshal.AllocHGlobal(SomeObjectSize);
IntPtr b = IntPtr(a.ToInt32());

over

IntPtr a = Marshal.AllocHGlobal(SomeObjectSize);
IntPtr b = a;

?


Solution

  • You not only can use

    IntPtr b = a;
    

    to hold the information used to obtain a pointer, but you should use this to ensure compatibility for different platforms.IntPtr is platform specific type (see there) and its size depends on the platform bitness to automatically fit the pointer size.

    However, the IntPtr is multipurpose type and it's intended not only to keep pointers information but also for various Windows API handles in order to be used in Win API interoperations (this however is mainly utilized by runtime and CTS and rarely by external applications). Many of the these handles (such as windows handles, icon handles, file handles, registry handles, etc.) have 32-bit size and that's where the IntPtr should be initialized with specifically sized integer and where the IntPtr(int value) constructor comes into play.