问题描述
前提条件
我将获得其指针的.net方法是:
- 公共静态方法
- 没有过载
- 参数和返回值仅是ValueType(不安全的指针,原始类型,非托管结构)
原因
获取方法指针,以便我可以在C ++程序中调用。
这对我有用,但是我需要为每个方法声明委托。
我想摆脱一遍又一遍的事情。
在.net端:
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
public delegate void UpdateDelegate(float delta);
public static void* GetUpdatePointer()
{
var delegateInstance = = new UpdateDelegate(Update);
var pfnUpdate = Marshal.GetFunctionPointerForDelegate(delegateInstance);
return (void*)pfnUpdate;
}
public static Update(float delta)=>{...}
在C ++方面:
typedef void (_stdcall * FuncPtr)(float);
void foo()
{
//just pseudo-code showing where is the pfnUpdate from.
FuncPtr pfnUpdate = (FuncPtr)GetUpdatePointer();
pfnUpdate(0.01f);
}
我想要什么
在c#中,我为我的本机代码导出GetMethodPointer。它将返回一个指向指定方法的函数指针,并且本机程序可以通过stdcall调用约定来调用此指针。
//avoid gc collect this object
static List<Delegate> KeepReference = new List<Delegate>();
public unsafe static void* GetMethodPointer(string name)
{
System.Reflection.MethodInfo methodInfo = typeof(PhysicsMain).GetMethod(name);
// also mark this delegate with [UnmanagedFunctionPointer(CallingConvention.StdCall)] attribute
Type delegateType = ConstructDelegateTypeWithMethodInfo(methodInfo);
var delegateInstance = Delegate.CreateDelegate(delegateType,methodInfo);
KeepReference.Add(delegateInstance);
return (void*)Marshal.GetFunctionPointerForDelegate(delegateInstance);
}
我需要ConstructDelegateTypeWithMethodInfo来创建一个具有与指定方法相同签名的委托。并为其标记[UnmanagedFunctionPointer(CallingConvention.StdCall)]属性,以便可以将其封送为函数指针。
我认为它可能使用IL,Reflection甚至Asm来做到这一点。或使用IL编写整个GetMethodPointer方法。
解决方法
在您的示例中,您假设方法的类是已知函数(PhysicsMain
)。
如果还知道UpdateDelegate
,则可以轻松使用它:
Type delegateType = typeof(UpdateDelegate);
var delegateInstance = Delegate.CreateDelegate(delegateType,methodInfo);
但是您也可以仅通过名称获得此类型:
Type delegateType = Type.GetType("Namespace.ClassName+UpdateDelegate");
var delegateInstance = Delegate.CreateDelegate(delegateType,methodInfo);
您可以查看delegateType.CustomAttributes
并确认类型具有UnmanagedFunctionPointer
属性。
最后,这几天我找到了解决方案。首先,我遇到了post给出的Expression.GetDelegateType
。但这对我不起作用,因为Marshal.GetFunctionPointerForDelegate
不支持Expression.GetDelegateType
生成的通用委托类型。我认为Expression.GetDelegateType
的实现可能会有一些线索。因此,我浏览了referencesource,并得到了一个名为MakeNewCustomDelegate
的内部方法。 link给出了有关如何调用内部方法的代码。事情很容易解决!
编辑:我忘了说了,委托的默认非托管调用约定是stdcall,因此我们不需要明确地用[UnmanagedFunctionPointer(CallingConvention.StdCall)]标记委托。