调用C++函数指针从C#
问题描述:
是否可以调用C(++)静态函数指针(不是委托)这样调用C++函数指针从C#
typedef int (*MyCppFunc)(void* SomeObject);
从C#?
void CallFromCSharp(MyCppFunc funcptr, IntPtr param)
{
funcptr(param);
}
我需要能够从c#回调到一些旧的C++类。 C++被管理,但类不是引用类(还)。
到目前为止,我不知道如何从c#中调用C++函数指针,有可能吗?
答
dtb是正确的。这里有一个更详细的Marshal.GetDelegateForFunctionPointer的例子。它应该适合你。
在C++:
static int __stdcall SomeFunction(void* someObject, void* someParam)
{
CSomeClass* o = (CSomeClass*)someObject;
return o->MemberFunction(someParam);
}
int main()
{
CSomeClass o;
void* p = 0;
CSharp::Function(System::IntPtr(SomeFunction), System::IntPtr(&o), System::IntPtr(p));
}
在C#:
public class CSharp
{
delegate int CFuncDelegate(IntPtr Obj, IntPtr Arg);
public static void Function(IntPtr CFunc, IntPtr Obj, IntPtr Arg)
{
CFuncDelegate func = (CFuncDelegate)Marshal.GetDelegateForFunctionPointer(CFunc, typeof(CFuncDelegate));
int rc = func(Obj, Arg);
}
}
答
看看Marshal.GetDelegateForFunctionPointer方法。
delegate void MyCppFunc(IntPtr someObject);
MyCppFunc csharpfuncptr =
(MyCppFunc)Marshal.GetDelegateForFunctionPointer(funcptr, typeof(MyCppFunc));
csharpfuncptr(param);
,我不知道这是否真的与你的C++方法可行,但正如MSDN文档指出:
获得函数指针您不能使用此方法,通过C++
我认为最好的方法是创建一个C++/CLI包装为。 – Anzurio 2010-03-18 15:26:32
这工作对我来说,https://*.com/questions/39790977/how-to-pass-a-delegate-or-function-pointer-from-c-sharp-to-c-and-call-it- 39803574#39803574 – 2017-11-09 07:30:05