Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between IntPtr and Marshal.ReadIntPtr?

I did like to understand what is the difference between:

new IntPtr(pointer.ToInt64() + 0x4);

and

Marshal.ReadIntPtr(pointer + 0x4);

They give out a different result but does it not do the same thing?

If possible could you provide a practical example to illustrate what my misconception of it is?

like image 764
Guapo Avatar asked Oct 28 '25 08:10

Guapo


1 Answers

IntPtr is basically platform-specific integer. It's 32 bit in 32-bit OS and 64 bit in 64-bit OS. It's commonly used to represent a pointer, but can as well represent any random integer.

So your two methods do different things. First (IntPtr constructor) just takes whatever number you provide and represent that as IntPtr. In this case it does not matter if IntPtr is valid memory address or not.

Marshal.ReadIntPtr is doing different thing: it treats whatever you pass to it as memory address, then it goes to that address, reads 4 or 8 bytes from there, and returns IntPtr representing that data.

Try this to verify:

IntPtr pointer = IntPtr.Zero;
var anotherPointer = new IntPtr(pointer.ToInt64() + 0x4);
var yetAnother = Marshal.ReadIntPtr(pointer + 0x4);

This will throw memory access violation exception on third line, because you cannot read memory at such low address (0x4) usually. Second line however just returns whatever you passed there (4) as IntPtr.

like image 128
Evk Avatar answered Oct 30 '25 23:10

Evk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!