4

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

4

3 回答 3

3

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

于 2013-04-10T11:35:21.353 回答
2

这是一个使用C++\Cli和的解决方案boost::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 可能会按照自己的意愿重新分配内存中的对象,但本机代码不会获得指向委托的直接指针,而是指向编组器生成的某些代码块的指针。这种间接确保本机函数指针即使在移动委托时也保持有效。

于 2013-04-10T11:46:08.980 回答
1

尝试使用Unmanaged Exports。我个人使用它从本地 C++ 应用程序调用 C# 函数。

于 2013-04-10T11:40:36.137 回答