Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a function from C++ to C#

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.

like image 620
mirc00 Avatar asked Oct 30 '22 15:10

mirc00


1 Answers

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
like image 147
InBetween Avatar answered Nov 08 '22 07:11

InBetween