C++ COM 对象作为属性

C++ COM object as property

本文关键字:属性 对象 COM C++      更新时间:2023-10-16

我需要我的库的一个对象,特别是作为一个属性,因为我在我的方法中需要它。

如果我将其声明为局部变量,它可以工作:

#import "...library.tlb"
int _tmain(int argc, _TCHAR* argv[])
{
    CoInitialize(NULL);
    RobstepRemoteLibraryCSharp::IRobstepPtr interf(__uuidof(RobstepRemoteLibraryCSharp::Robstep));
    std::wcout << interf->Test() << std::endl;
    interf->ConnectToPlattform("192.168.0.1");
}

这有效并完全符合它应该做的事情。但是如何获取"interf"变量作为属性呢?到目前为止,我尝试了不同的东西。

文件.h

#import "...library.tlb"
class robstep
{
public:
    robstep(void);
    ~robstep(void);
private:
    CComPtr interf; //Version 1
    CComObject<RobstepRemoteLibraryCSharp::Robstep>* interf; //Version 2
}

文件.cpp

#import "...library.tlb"
robstep::robstep(void)
{
    CoInitialize(NULL);
    interf.CoCreateInstance(__uuidof(RobstepRemoteLibraryCSharp::Robstep)); //Version 1
    CComObject<RobstepRemoteLibraryCSharp::Robstep>::CreateInstance(&interf); //Version 2
}

我使用了这个链接和这个

我必须投掷它或类似的东西吗?

您应该使用第一个选项 CComPtr<Interface>

但是,如果要导入 TLB,则通过#import应该会生成一些可以使用的智能指针模板。

RobstepRemoteLibraryCSharp::IRobstepPtr interf;
interf.CreateInstance(__uuidof(Class));

除了公认的答案之外,这是我对这个问题的解决方案:

CComPtr<RobstepRemoteLibraryCSharp::IRobstep> interf;
interf.CoCreateInstance(__uuidof(RobstepRemoteLibraryCSharp::Robstep));