猿问

非托管 c++ DLL 从 c# 获取结构

是否可以从 c++ DLL 调用 c# 中的方法?


我有良好的沟通 c# -> C++ ,但我希望能够发起呼叫 C++ -> c# 来轮询一些数据


我的代码看起来像这样......


主机.h


/*

define the exporter for the C API

*/

#ifdef DLL_EXPORT

#define DLL_EXPORT __declspec(dllexport) 

#else

#define DLL_EXPORT __declspec(dllimport) 

#endif

class myClass

{

public:

    myCLass(){

        //do some initialising

    }

    ~myCLass(){

        //do some tidying

    }


    int getInt(int target) {

        switch (target)

        { 

        case 0:

            return someIntValue; 

        case 1:

            return someOtherIntValue;

        default:

            return 0;

        }

    }


   std::string getString(int target) {

        switch (target)

        { 

        case 0:

            return someStringValue;

        case 1:

            return someOtherStringValue;

        default:

            return "";

        }

    }

}


extern "C" {

    DLL_EXPORT  myClass* myClassConstructor();

    DLL_EXPORT void DestroySpatialser(const myClass* _pContext);

    DLL_EXPORT int getInt(myClass* _pContext, int target);

    DLL_EXPORT void getString(myClass* _pContext, int target, __out BSTR* returnStr);


}

主机.cpp


extern "C" {



    myClass* myClassConstructor()

    {

        return new myClass();

    }


    void myClassDestructor(const myClass* _pContext)

    {

        if (_pContext != nullptr)

        {

            _pContext->~myClass();

            delete _pContext;

        }

    }


    //example

    int getInt(myClass* _pContext, int target)

    {

        if (_pContext == nullptr)

        {

            return K_ERR_INT;

        }

        return _pContext->getInt(target);

    }


    void getString(myClass* _pContext, int target, __out BSTR* returnStr)

    {

        std::string str;

        if (_pContext == nullptr)

        {

            str = K_ERR_CHAR;

        }

        else {

            str = _pContext->getString(target);

        }

        const std::string stdStr = str;

        _bstr_t bstrStr = stdStr.c_str();

        *returnStr = bstrStr.copy();

    }

}



这一切都很好。


我想添加从 .cs 应用程序(它将是 3 个浮点数的结构)中获取值的功能,该应用程序应该从 myClass 的实例中调用。


我不想在 c# 端启动它(我知道该怎么做)。


有什么建议吗?


人到中年有点甜
浏览 187回答 2
2回答

忽然笑

好吧,我能想到的一种方法是将 JSON 字符串作为 char 数组从 C++ 传递到 C#,然后在 C# 上解析它并获取数据。这是两种语言都熟悉的一种交流方式。此外,您需要将回调从 C# 传递到 C++ 以允许这样做,就像在这个问题中解释的那样。让我知道这是否有帮助:)

慕少森

使您的 C# 类型为 COMVisible,这意味着您将能够从支持 COM 的 C++ 代码调用它们,例如,使用ATL。
随时随地看视频慕课网APP
我要回答