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

标签 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
}

当您想在 C++ 中从内存中读取数据时,这非常有用,因为它是通用的:您可以使用 Read<"int">(0x00)"Read<"vector">(0x00)并将其全部集中在一个功能中。

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

最佳答案

这样的事情行不通吗?

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

关于c# - 将函数从 C++ 转换为 C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33691106/

相关文章:

java - 如何处理java中的类型有界通配符

c# - 文件关联如何填充 ProgId 和 ApplicationName

c# - 从项目文件构建一个没有 Microsoft Visual Studio 的可执行文件

c++ - 使用 scanf() 进行动态分配

c++ - 奇怪的语法:范围运算符 (::) 后的星号?

Java 嵌套自引用泛型

c# - 如何声明要由泛型类型使用的枚举?

c# - 在 linq to entities 查询中获取子项计数

c# - xUnit 测试引擎的 InlineDataAttribute + 可选方法参数

c++ - glDrawElements 只绘制索引指定的第一个三角形