6

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.

Community
  • 1
  • 1
Patryk
  • 3,042
  • 11
  • 41
  • 83
  • Here is an article you can look at that will help understand how to do what it is you are wanting to do also try using the key word unsafe as well http://blog.rednael.com/2008/08/29/MarshallingUsingNativeDLLsInNET.aspx – MethodMan Feb 29 '12 at 14:47
  • Here is how to do it (.Net) without `unsafe` https://stackoverflow.com/a/75362556/3351489 – CorrM Feb 07 '23 at 00:16

2 Answers2

7

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();
dice
  • 2,820
  • 1
  • 23
  • 34
2

You can use an Encoding.GetString() to convert the bytes to a string. Which encoding to use depends on the encoding of the string, e.g. Encoding.UTF8.GetString(pointer_arrays, 0) for UTF8 encoding, Encoding.Unicode for unicode, Encoding.ASCII for ASCII or Encoding.Default for the default code page of your system.

Andre Loker
  • 8,368
  • 1
  • 23
  • 36