为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

C#
人到中年有点甜 2022-06-18 17:48:49
是否可以从 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) #endifclass 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);}主机.cppextern "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# 端启动它(我知道该怎么做)。有什么建议吗?
查看完整描述

2 回答

?
忽然笑

TA贡献1806条经验 获得超5个赞

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



查看完整回答
反对 回复 2022-06-18
?
慕少森

TA贡献2019条经验 获得超9个赞

使您的 C# 类型为 COMVisible,这意味着您将能够从支持 COM 的 C++ 代码调用它们,例如,使用ATL



查看完整回答
反对 回复 2022-06-18
  • 2 回答
  • 0 关注
  • 186 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号