Can the following snippet be converted 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 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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With