How to convert byte[] array to IntPtr?

Patryk picture Patryk · Feb 29, 2012 · Viewed 12.9k times · Source

Possible Duplicate:
How to get IntPtr from byte[] in C#

I'm reading strings from memory with

byte[] array = 
reader.ReadProcessMemory((IntPtr)address, (uint)255, out bytesReadSize);

and then I'm converthing this array to string.

I've got a problem now coz under the address 003A53D4 in program's memory there is a pointer, which points to a string. How can I get string's address? Thanks :)

THATS WHAT I TRIED:

IntPtr pointers_address = new IntPtr(module_base_address + 3822548);
byte[] pointer_arrays = 
reader.ReadProcessMemory(pointers_address, (uint)16, out bytesReadSize2); 
IntPtr pointer_for_string = new IntPtr();
Marshal.Copy(pointers_array, 0, pointer_for_string, 16);

It says (about 4th line):

Value cannot be null. Parameter name: destination

and when I change new IntPtr() to new IntPtr(1) it says

Attempted to read or write protected memory. This is often an indication that other memory is corrupt.

Answer

dice picture dice · Feb 29, 2012

The best way (IMO) is the following:

GCHandle pinned = GCHandle.Alloc(array , GCHandleType.Pinned);
IntPtr address = pinned.AddrOfPinnedObject();
reader.ReadProcessMemory(address, (uint)255, out bytesReadSize);
pinned.Free();