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#?
views:
50answers:
2
+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
2010-10-12 14:57:25
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
2010-10-12 15:00:06
@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
2010-10-12 15:03:20
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
2010-10-12 15:14:06
@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
2010-10-12 15:28:20
+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
2010-10-13 15:55:08