从c++调用c#事件

Calling C# event from C++

本文关键字:事件 调用 c++      更新时间:2023-10-16

我想知道从c++代码调用c#代码的最佳实践是什么?我到底想要什么:我已经写了c++代码,当用户使用这个程序时,遇到c++代码中的某些函数,我想调用另一个c#代码来执行其他东西,所以它就像语言之间的委托。我怎样才能最好地做到这一点?到目前为止,我的想法是:在c#中我可以创建web服务,然后用c++调用它。

我建议将c#类导出为com可见类。

这里是使用C++Cliboost::function的解决方案

本地代码:

typedef void MemberFunctionPointerType(int x);
class NativeClass
{
public:
    //I used boost but any function pointer will work
    void setDelegate(boost::function<MemberFunctionPointerType> delegate)
        {
            m_delegate = delegate;
        }
    void DoSomeThing()
        {
            int x;
            //do your logic here
            ...
            ...
            ...
            //when the needed event occurs call the callbackfunction so the class which registered to event will get his function called.
            m_delegate(x);                     
private:
    boost::function<MemberFunctionPointerType> m_delegate;        
};        

托管代码:

typedef MemberFunctionPointerType* CallbackFunctionType;
delegate void CallbackFuncDelegate;
class ManagedClass
{
public:
    ManagedClass()
    {
        m_delegate = gcnew CallbackFuncDelegate(this,&ManagedClass::CallBackFunction);
        m_native = new NativeClass();
        //register the delegate;
        boost::function<MemberFunctionPointerType> funcPointer(static_cast<CallbackFunctionType>(Marshal::GetFunctionPointerForDelegate(m_delegate).ToPointer()));
        m_native->setDelegate(funcPointer);
    }
    //the callback function will be called every time the nativeClass event occurs.
    void CallBackFunction()
    {
        //do your logic or call your c# method
    }
private:
    CallbackFuncDelegate^ m_delegate ;
    NativeClass* m_native;    
};

那么为什么这个可以工作并且垃圾收集器不会破坏一切呢?在处理GC时,有两件事需要担心:

1)委托集合:只要ManagedClass还活着,委托就不会被收集。所以我们不必担心它。

2)重新分配:GC可能会在内存中重新分配对象,但本机代码不会获得指向委托的直接指针,而是指向由封送处理程序生成的一些代码块的指针。这种间接确保即使委托被移动,本机函数指针仍然有效。

尝试使用非托管导出。我个人使用它从本地c++应用程序调用c#函数。