首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >C#函数指针?

C#函数指针?
EN

Stack Overflow用户
提问于 2012-03-18 07:19:50
回答 6查看 98.5K关注 0票数 27

我在使用C#时遇到了一个问题,我想在我的代码中获得一个方法的指针,但这似乎是不可能的。我需要该方法的指针,因为我想使用WriteProcessMemory对其进行无操作。我怎样才能得到指针?

示例代码

代码语言:javascript
复制
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.
}
EN

回答 6

Stack Overflow用户

发布于 2013-02-26 07:19:57

我知道这很古老,但是C#中类似函数指针的例子应该是这样的:

代码语言:javascript
复制
class Temp 
{
   public void DoSomething() {}
   public void DoSomethingElse() {}
   public void DoSomethingWithAString(string myString) {}
   public bool GetANewCat(string name) { return true; }
}

然后在你的main或任何地方使用...and:

代码语言:javascript
复制
var temp = new Temp();
Action myPointer = null, myPointer2 = null;
myPointer = temp.DoSomething;
myPointer2 = temp.DoSomethingElse;

然后调用原始函数,

代码语言:javascript
复制
myPointer();
myPointer2();

如果你的方法有参数,那么就像在Action中添加泛型参数一样简单:

代码语言:javascript
复制
Action<string> doItWithAString = null;
doItWithAString = temp.DoSomethingWithAString;

doItWithAString("help me");

或者,如果您需要返回值:

代码语言:javascript
复制
Func<string, bool> getACat = null;
getACat = temp.GetANewCat;

var gotIt = getACat("help me");
票数 44
EN

Stack Overflow用户

发布于 2012-03-18 07:37:49

编辑:我误读了您的问题,并且没有看到希望NOP语句与执行原始内存操作有关的内容。我恐怕不推荐这样做,因为正如Raymond Chen所说,GC在内存中移动东西(因此在C#中有'pinned‘关键字)。您可能可以使用反射来实现,但您的问题表明您对CLR没有很好的掌握。无论如何,回到我最初不相干的回答(我以为你只是想知道如何使用委托的信息):

C#不是一种脚本语言;)

无论如何,C# (和CLR)都有“函数指针”-除了它们被称为“委托”并且是强类型的,这意味着除了你想要调用的函数之外,你还需要定义函数的签名。

在你的例子中,你会有这样的东西:

代码语言:javascript
复制
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);
}
票数 23
EN

Stack Overflow用户

发布于 2013-12-03 15:47:33

代码语言:javascript
复制
public string myFunction(string name)
{
    return "Hello " + name;
}

public string functionPointerExample(Func<string,string> myFunction)
{
    return myFunction("Theron");
}

Func functionName..使用它来传递方法。在这个上下文中没有任何意义,但这基本上就是您使用它的方式。

票数 15
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/9754669

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档