本文介绍了调用C ++从C#函数指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否有可能调用C(++)静态函数指针(不是委托)这样
Is it possible to call a c(++) static function pointer (not a delegate) like this
typedef int (*MyCppFunc)(void* SomeObject);
从C#?
void CallFromCSharp(MyCppFunc funcptr, IntPtr param)
{
funcptr(param);
}
我需要能够从C#回调到一些老的C ++类。 C ++进行管理,但这些类不是裁判班(还)。
I need to be able to callback from c# into some old c++ classes. C++ is managed, but the classes are not ref classes (yet).
到目前为止,我还是不知道如何调用从C#C ++函数指针,这可能吗?
So far I got no idea how to call a c++ function pointer from c#, is it possible?
推荐答案
DTB是正确的。此处Marshal.GetDelegateForFunctionPointer一个更详细的例子。它应该为你工作。
dtb is right. Here a more detailed example for Marshal.GetDelegateForFunctionPointer. It should work for you.
在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);
}
}
这篇关于调用C ++从C#函数指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!