Reputation: 3482
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?
Upvotes: 4
Views: 1805
Reputation: 101543
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
.
Upvotes: 3