简体   繁体   English

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

[英]Converting a function from C++ to C#

Can the following snippet be converted to C#.NET? 可以将以下代码段转换为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
}

This is really helpful when you want to read data from memory in C++ because it's generic: you can use Read<"int">(0x00)" or Read<"vector">(0x00) and have it all in one function. 当你想用C ++从内存中读取数据时,这非常有用,因为它是通用的:你可以使用Read<"int">(0x00)"Read<"vector">(0x00)并将它全部放在一个函数中。

In C#.NET, it's not working for me because, to read memory, you need the DLLImport ReadProcessMemory which has pre-defined parameters, which are not generic of course. 在C#.NET中,它对我不起作用,因为要读取内存,需要DLLImport ReadProcessMemory,它具有预定义的参数,当然这些参数不是通用的。

Wouldn't something like this work? 不会像这样的工作吗?

using System.Runtime.InteropServices;

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

This would only work with structures, you'd need to consider marshalling strings like a special non generic case if you need it. 这只适用于结构,如果需要,您需要考虑编组字符串,如特殊的非通用情况。

A simple check to see if it works: 一个简单的检查,看它是否有效:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM