【问题标题】:Calling C# event from C++从 C++ 调用 C# 事件
【发布时间】:2013-04-02 05:21:37
【问题描述】:

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

【问题讨论】:

  • 考虑将 C# 类设为 COM 对象,以便您可以直接从 C++ 调用它

标签: c# c++ com function-pointers


【解决方案1】:

我建议将 C# 类导出为 com 可见类。然后在 C++ 中使用它们。

【讨论】:

    【解决方案2】:

    这是使用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 可能会重新分配内存中的对象,但本机代码不会获得指向委托的直接指针,而是指向由封送拆收器生成的某些代码块的指针。 这种间接确保即使委托被移动,本机函数指针仍然有效。

    【讨论】:

      【解决方案3】:

      尝试使用Unmanaged Exports。我个人使用它来调用原生 C++ 应用程序中的 C# 函数。

      【讨论】:

        猜你喜欢
        • 2010-12-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-10
        • 2015-04-27
        • 2017-06-12
        • 1970-01-01
        • 2022-01-19
        相关资源
        最近更新 更多