c# Call a method by memory address

时光毁灭记忆、已成空白 提交于 2020-04-11 04:47:35

问题


I am trying to call a function at a specified memory address in c#, here is how I would go about it in C:

typedef void _do(int i);
auto doActor = (_do*)0xAAAABEEF;
doActor(1);

How do I replicate this behavior in C# if at all possible? Very new to C# all help is appreciated.

More in depth explanation of my situation: I am trying to create a tool that helps me automate certain processes within an executable. I decompiled the assembly of the main API and added my functionality (for the most part) by intercepting network packets/spoofing my own. I do not have control over the client side of things, stored in an obfuscated assembly that I can't de-/recompile. I seldomly need to call one or two functions out of this obfuscated assembly and I found the memory addresses of those relevant functions using a debugger but don't know where to go from here in c#.


回答1:


The closest equivalent to a C function pointer in C# is a delegate. Delegates are managed, but you can convert one from the other with the Marshal.GetDelegateForFunctionPointer method:

public delegate void _do(int i); // the delegate type

var ptr = new IntPtr(0xAAAABEEF);
var doActor = Marshal.GetDelegateForFunctionPointer<_do>(ptr);
doActor(1);

There are limitations tied to this API, however. I suggest you take a look at the documentation.

If you're stuck with a version of .NET older than 4.5, you're going to have to use a different version of GetDelegateForFunctionPointer:

var doActor = (_do)Marshal.GetDelegateForFunctionPointer(ptr, typeof(_do));


来源:https://stackoverflow.com/questions/51991689/c-sharp-call-a-method-by-memory-address

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!