How to print Address of a method in c#?

安稳与你 提交于 2021-02-17 06:01:21

问题


In C Programming,

void foo()
{
}
void main()
{
  printf("%p",foo);
}

will print the address of foo function. Please let me know if there is a way in C# to achieve the same.


回答1:


C# is a high-level language. A method does not need to have an "address" -- this is an implementation detail left to the runtime.

However, if you need to interface with C code that requires a method address (for example, to provide a callback to a Windows API method), you can

  • create a delegate and
  • retrieve a function pointer to that delegate.

Example:

static void foo()
{
}

static void Main(string[] args)
{
    Delegate fooDelegate = new Action(foo);

    IntPtr p = Marshal.GetFunctionPointerForDelegate(fooDelegate);

    Console.WriteLine(p);
}

Note, though, that you usually won't need this. Even for the aforementioned example -- passing a callback to a Windows API function -- there are more elegant solutions.




回答2:


In C# methods don't provide address. In C method addresses are available to create pointers to functions that can be used to alternatively call functions by passing them to functions that accept these pointers. In C# you could achieve the same using delegates that are typesafe and these delegates can contain multiple functions too...



来源:https://stackoverflow.com/questions/25464493/how-to-print-address-of-a-method-in-c

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