How to print Address of a method in c#?

后端 未结 2 1063
不知归路
不知归路 2021-01-29 02:04

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

2条回答
  •  清酒与你
    2021-01-29 02:25

    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.

提交回复
热议问题