use*_*333 24 c# methods pointers
我遇到了C#的问题,我想在我的代码中得到一个方法指针,但似乎不可能.我需要方法的指针,因为我想使用WriteProcessMemory来禁止它.我怎么得到指针?
示例代码
main()
{
function1();
function2();
}
function1()
{
//get function2 pointer
//use WPM to nop it (I know how, this is not the problem)
}
function2()
{
Writeline("bla"); //this will never happen because I added a no-op.
}
Run Code Online (Sandbox Code Playgroud)
out*_*red 35
我知道这很老了,但是像C#中的函数指针这样的例子就是这样的:
class Temp
{
public void DoSomething() {}
public void DoSomethingElse() {}
public void DoSomethingWithAString(string myString) {}
public bool GetANewCat(string name) { return true; }
}
Run Code Online (Sandbox Code Playgroud)
......然后在你的主要或任何地方:
var temp = new Temp();
Action myPointer = null, myPointer2 = null;
myPointer = temp.DoSomething;
myPointer2 = temp.DoSomethingElse;
Run Code Online (Sandbox Code Playgroud)
然后调用原始函数,
myPointer();
myPointer2();
Run Code Online (Sandbox Code Playgroud)
如果您的方法有参数,那么就像在Action中添加泛型参数一样简单:
Action<string> doItWithAString = null;
doItWithAString = temp.DoSomethingWithAString;
doItWithAString("help me");
Run Code Online (Sandbox Code Playgroud)
或者,如果您需要返回一个值:
Func<string, bool> getACat = null;
getACat = temp.GetANewCat;
var gotIt = getACat("help me");
Run Code Online (Sandbox Code Playgroud)
Dai*_*Dai 22
编辑:我误读了你的问题,并没有看到有关想要NOP做一个声明做原始内存操作.我担心这不推荐,因为正如Raymond Chen所说,GC会在内存中移动内容(因此C#中的'pinned'关键字).你可能可以用反射来做,但你的问题表明你没有对CLR的强烈掌握.无论如何,回到我原来无关的答案(我认为你只想要如何使用代表的信息):
C#不是脚本语言;)
无论如何,C#(和CLR)有"函数指针" - 除了它们被称为"委托"并且是强类型的,这意味着除了要调用的函数之外,还需要定义函数的签名.
在你的情况下,你会有这样的事情:
public static void Main(String[] args) {
Function1();
}
// This is the "type" of the function pointer, known as a "delegate" in .NET.
// An instance of this delegate can point to any function that has the same signature (in this case, any function/method that returns void and accepts a single String argument).
public delegate void FooBarDelegate(String x);
public static void Function1() {
// Create a delegate to Function2
FooBarDelegate functionPointer = new FooBarDelegate( Function2 );
// call it
functionPointer("bla");
}
public static void Function2(String x) {
Console.WriteLine(x);
}
Run Code Online (Sandbox Code Playgroud)
小智 14
public string myFunction(string name)
{
return "Hello " + name;
}
public string functionPointerExample(Func<string,string> myFunction)
{
myFunction("Theron");
}
Run Code Online (Sandbox Code Playgroud)
Func functionName ..用它来传递方法.在这种情况下没有任何意义,但这基本上就是你如何使用它
小智 5
其实C#9中引入了真正的函数指针
从链接:
您可以使用语法定义函数指针delegate*。编译器将使用指令调用函数,calli而不是实例化委托对象并调用Invoke
帖子中的示例示例:
static unsafe void function1()
{
//get function2 pointer
delegate*<void> ptr = &function2;
// do something with ptr
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
85359 次 |
| 最近记录: |