Converting a function from C ++ to C #

Is it possible to convert the following snippet to 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 useful when you want to read data from memory in C ++, because it is general: you can use Read<"int">(0x00)" or Read<"vector">(0x00) and have it all in one functions.

In C # .NET, it does not work for me, because for reading memory you need the DLLImport ReadProcessMemory library, which has predefined parameters, which, of course, are not shared.

+5
source share
1 answer

Wouldn’t it be like this job?

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

This will only work with structures, you will need to consider sorting strings as special not general if you need it.

A simple check to make sure 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 
+2
source

Source: https://habr.com/ru/post/1235872/


All Articles