How to best convert CString to BSTR to pass it as an “in” parameter into a COM method?

前端 未结 3 732
心在旅途
心在旅途 2021-01-12 03:18

I need to convert a CString instance into a properly allocated BSTR and pass that BSTR into a COM method. To have code that compiles a

3条回答
  •  悲哀的现实
    2021-01-12 03:41

    CComBSTR has overloaded constructors for both char* and wchar_t*, which make the call to SysAllocString() on your behalf. So the explicit allocation in your code snippet is actually unnecessary. The following would work just as well:

    ATL::CComBSTR converted = sourceString;
    interface->CallMethod(converted);
    

    Furthermore, if you have no need to use the converted BSTR elsewhere in your code, you can perform the object construction in-place in the method call, like so:

    interface->CallMethod(ATL::CComBSTR(sourceString));
    

    The same applies to the _bstr_t class, which can be used instead of CComBSTR if you don't want a dependency on the ATL.

提交回复
热议问题