将函数从C++转换为C#

mir*_*c00 5 c# c++ generics readprocessmemory

可以将以下代码段转换为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
}
Run Code Online (Sandbox Code Playgroud)

当你想用C++从内存中读取数据时,这非常有用,因为它是通用的:你可以在一个函数中使用Read<"int">(0x00)"或者Read<"vector">(0x00)全部使用它.

在C#.NET中,它对我不起作用,因为要读取内存,需要DLLImport ReadProcessMemory,它具有预定义的参数,当然这些参数不是通用的.

InB*_*een 2

这样的事情行不通吗?

using System.Runtime.InteropServices;

public static T Read<T>(IntPtr ptr) where T : struct
{
   return (T)Marshal.PtrToStructure(ptr, typeof(T));
}
Run Code Online (Sandbox Code Playgroud)

这仅适用于结构,如果需要,您需要考虑将字符串编组为特殊的非通用情况。

一个简单的检查来看看它是否有效:

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
Run Code Online (Sandbox Code Playgroud)