views:

1586

answers:

3

Hello,

I need to call VirtualAllocEx and it returns IntPtr. I call that function to get an empty address so I can write my codecave there(this is in another process).

How do I convert the result into UInt32,so I could call WriteProcessMemory() lately with that address?

+1  A: 

When you call WriteProcessMemory, you should be passing an IntPtr for the address rather than a UInt32 (because WriteProcessMemory expects a pointer, not an integer). So you should be able to use the IntPtr returned by VirtualAllocEx directly without the need to convert it to a UInt32.

itowlson
[DllImport("kernel32.dll")] private static extern Boolean WriteProcessMemory(IntPtr hProcess, uint lpBaseAddress,byte[] lpBuffer, int nSize, IntPtr lpNumberOfBytesWritten);No.And I can't change it,because I also use VirtualQueryEx,which also returns uint.Can't i convert IntPtr to UInt?
John
VirtualQueryEx returns the size of the block, not a pointer. I fail to see the problem.
Roger Lipscombe
VirtualQueryEx should also take an IntPtr for its lpAddress parameter. Basically wherever you see a memory handle in Win32, you should be thinking IntPtr (the native pointer type) rather than Int32 or UInt32. On 32-bit platforms IntPtr and Int32/UInt32 are the same, so you can call IntPtr.ToInt32, or cast to UInt32, but why not use IntPtr throughout? It is more portable and more intention-revealing.
itowlson
+1  A: 

You could just cast it with (uint)ptr I believe (If it won't cast nicely, try ptr.ToInt32() or ToInt64() first. At least I don't know of any issues with this approach, haven't used it -that- much though. Given UInt32 has larger range than Int32 and same as Int64 on non-negative side it should be good enough.

Although not sure how the Int32 behaves on 64 bit architectures. Badly I'd imagine as the reason for IntPtr is to provide platform independant way to store pointers.

Mikko Rantanen
A: 

Your DLlImport for WriteProcessMemory is incorrect, base address is a pointer so it should be defined as IntPtr.

MSDN

You need to fix your DllImport statement.

Steven