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

前端 未结 3 725
心在旅途
心在旅途 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:35

    One of _bstr_t constructors allows you to simply attach to existing BSTR so that you can have the exception that you want from CString::AllocSysString when BSTR allocation fails.

    // _bstr_t simply attaches to BSTR, doesn't reallocate it
    interface->CallMethod( _bstr_t(sourceString.AllocSysString(), false) );
    

    The _bstr_t constructor documentation says:

    _bstr_t(
       BSTR bstr,
       bool fCopy 
    );
    

    fCopy
    If false, the bstr argument is attached to the new object without making a copy by calling SysAllocString.

    On the other hand, CComBSTR constructor doesn't seem to have the corresponding signature; although it can be used as well if BSTR allocation failure exception is not really needed, as mentioned by Phil Booth in his answer.

提交回复
热议问题