可以将以下代码段转换为C#.NET吗?
template <class cData>
cData Read(DWORD dwAddress)
{
cData cRead; //Generic Variable To Store Data
ReadProcessMemory(hProcess, (LPVOID)dwAddress, &cRead, sizeof(cData), NULL); //Win API - Reads Data At Specified Location
return cRead; //Returns Value At Specified dwAddress
}
当您想要在C ++中从内存中读取数据时,这非常有用,因为它是通用的:您可以使用Read<"int">(0x00)"
或Read<"vector">(0x00)
并将其全部放在一个函数中。
在C#.NET中,它对我不起作用,因为要读取内存,你需要DLLImport ReadProcessMemory,它有预定义的参数,当然不是通用的。
答案 0 :(得分:2)
不会有这样的工作吗?
using System.Runtime.InteropServices;
public static T Read<T>(IntPtr ptr) where T : struct
{
return (T)Marshal.PtrToStructure(ptr, typeof(T));
}
这只适用于结构,如果需要,您需要考虑编组字符串,如特殊的非通用情况。
简单检查一下它是否有效:
var ptr = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(int)));
var three = 3;
Marshal.StructureToPtr(three, ptr, true);
var data = Read<int>(ptr);
Debug.Assert(data == three); //true