views:

50

answers:

2

in cil code, ldftn is used to get the function pointer address to call the delegate constructor(i.e. .ctor(object, native int)).
How to get the function pointer used to construct delegate in C#?

+2  A: 

If you're looking for how the Reflection.Emit code should look, then something like this:

il.Emit(OpCodes.Ldftn, yourMethodInfo);
il.Emit(OpCodes.Newobj, yourDelegateType.GetConstructors()[0]);

The first line loads the function pointer onto the stack. The second line "passes" it to the constructor of the delegate. yourDelegateType should be something like typeof(Func<string>), etc.

Kirk Woll
Yes, that's a way to create delegate in Reflection.Emit. But i only want the function pointer i.e. the output of ldftn
Kii
@Kii, what do you want to do with it? Can you provide some (pseudo) code that illustrates what you'd like to accomplish?
Kirk Woll
once upon a time, there is a method:object create_object(object[] args) then i want to create a delegate through the method : object _delegate = create_object(new object[] { null , get_ptr(method_info) });
Kii
@Kii, but why is it not sufficient for create_object to return the delegate? That's the only thing that can be passed around natively in C# wrt to function pointers.
Kirk Woll
+1  A: 

Your question is phrased in a way that makes it hard to understand what you're actually trying to do. I think that perhaps what you want is something like this:

MethodInfo mi = ...
var ptr = mi.MethodHandle.GetFunctionPointer();
// now call a delegate .ctor using that ptr
kvb