C++ COM 对象作为 属性

C++ COM object as property

我需要我的库中的一个对象,尤其是 属性,因为我的方法中需要它。

如果我将它声明为局部变量,它会起作用:

#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" 变量作为 属性?到目前为止,我尝试了不同的方法。

file.h

#import "...\library.tlb"

class robstep
{
public:
    robstep(void);
    ~robstep(void);

private:
    CComPtr interf; //Version 1
    CComObject<RobstepRemoteLibraryCSharp::Robstep>* interf; //Version 2
}

file.cpp

#import "...\library.tlb"

robstep::robstep(void)
{
    CoInitialize(NULL);

    interf.CoCreateInstance(__uuidof(RobstepRemoteLibraryCSharp::Robstep)); //Version 1
    CComObject<RobstepRemoteLibraryCSharp::Robstep>::CreateInstance(&interf); //Version 2

}

我用过这个link and this one

我是否必须施放它或类似的东西?

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

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

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

除了已接受的答案外,这是我对这个问题的解决方案:

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