如何将byte[]数组转换为IntPtr?

6

我正在使用以下方法从内存中读取字符串:

可能有重复问题:
如何在C#中从byte[]获取IntPtr

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

然后我将这个数组转换为字符串。

现在我有一个问题,因为程序内存中的地址003A53D4下有一个指针,它指向一个字符串。我怎样才能获取字符串的地址?谢谢 :)

我尝试的方法:

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);

错误信息 (第四行):

值不能为 null。参数名: destination

当我将 new IntPtr() 更改为 new IntPtr(1) 时,错误信息如下:

尝试读取或写入受保护的内存。这通常是其他内存已损坏的迹象。


这里有一篇文章可以帮助你理解如何做你想做的事情,同时也尝试使用关键词unsafe。http://blog.rednael.com/2008/08/29/MarshallingUsingNativeDLLsInNET.aspx - MethodMan
这是如何在不使用 unsafe 的情况下完成它(.Net)的方法 https://stackoverflow.com/a/75362556/3351489 - CorrM
这里是如何在.Net中完成它而不使用unsafe的方法。请参考https://stackoverflow.com/a/75362556/3351489。 - CorrM
2个回答

7
最好的方式(以我的观点)如下所示:
GCHandle pinned = GCHandle.Alloc(array , GCHandleType.Pinned);
IntPtr address = pinned.AddrOfPinnedObject();
reader.ReadProcessMemory(address, (uint)255, out bytesReadSize);
pinned.Free();

2
您可以使用Encoding.GetString()将字节转换为字符串。使用哪种编码取决于字符串的编码方式,例如对于UTF8编码,可以使用Encoding.UTF8.GetString(pointer_arrays, 0),对于Unicode编码,可以使用Encoding.Unicode,对于ASCII编码,可以使用Encoding.ASCII,对于系统默认代码页,可以使用Encoding.Default。请注意保留HTML标签。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接