如何将ATL com类对象作为参数传递给COM

时间:2016-03-11 07:05:20

标签: c++ com atl

this thread类似,但是当我将一个字符串传递给方法时,com类中的字符串是错误的,这里是代码:

com server - Com.idl:

interface IParamClass : IUnknown
{
    [] HRESULT SetString([in] BSTR str);
}

interface IMyClass : IUnknown
{
    [] HRESULT PassComClassAsParam([in] IParamClass* parm);
}

ParamClass.cpp

class ATL_NO_VTABLE CParamClass : ...
{
...
public:
    BSTR m_str;

    STDMETHOD(SetString)(BSTR str);
};

STDMETHODIMP CParamClass::SetString(BSTR str)
{
    m_str = str;
    return S_OK;
}

MyClass.cpp:

STDMETHODIMP CMyClass::PassComClassAsParam( IParamClass* param)
{
    CParamClass *obj = (CParamClass*)param;
    BSTR str = obj->m_str;    //debugging here, is wrong string
...
}

C#客户端:

MyClass myobj = new MyClass();
ParamClass param = new ParamClass();
param.SetString("Test String!");
myobj.PassComClassAsParam(param);

1 个答案:

答案 0 :(得分:2)

您必须在此处复制字符串参数,因为您无法控制值的生命周期:

STDMETHODIMP CParamClass::SetString(BSTR str)
{
    m_str = str; // str is valid here, but you don't know when
                 // the value is destroyed later
    return S_OK;
}

当您通过m_str变量使用该值时,该字符串已被释放并销毁,因此您会看到它"错误"。

典型的解决方案是:

class ATL_NO_VTABLE CParamClass : ...
{
...
public:
    CComBSTR m_str; // <<--- Note CComBSTR

    STDMETHOD(SetString)(BSTR str);
};

STDMETHODIMP CParamClass::SetString(BSTR str)
{
    m_str = str;
    return S_OK;
}