2013-04-10 54 views
4

我想知道从C++代码调用c#代码的最佳做法是什么?我想要的是:我已经编写了C++代码,当用户使用该程序并在C++代码中遇到某些函数时,我想调用另一个c#代码来执行其他操作,所以它像语言之间的代理一样。我怎么能最好地完成这个?我到目前为止的想法是:在C#中,我可以制作Web服务,然后用C++调用它。从C++调用C#事件

+1

考虑让C#类成为COM对象,以便您可以直接从C++中调用它 – 2013-04-10 11:35:01

回答

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

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