如何最好地将CString转换为BSTR,将其作为“in”参数放入COM方法? [英] How to best convert CString to BSTR to pass it as an "in" parameter into a COM method?
问题描述
我需要将 CString
实例转换为正确分配的 BSTR
,并传递 BSTR
转换为COM方法。要有ANSI和Unicode编译和工作的代码,我使用 CString :: AllocSysString()
来转换任何格式 CString
到Unicode BSTR。
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 and works indentically for both ANSI and Unicode I use CString::AllocSysString()
to convert whatever format CString
to a Unicode BSTR.
由于没有拥有返回的BSTR,我需要处理它,并在最安全的方式调用后释放它
Since noone owns the returned BSTR I need to take care of it and release it after the call is done in the most exception-safe manner posible and with as little code as possible.
目前我使用 ATL :: CComBSTR
进行生命周期管理:
Currently I use ATL::CComBSTR
for lifetime management:
ATL::CComBSTR converted;
converted.Attach( sourceString.AllocSysString() ); //simply attaches to BSTR, doesn't reallocate it
interface->CallMethod( converted );
我不喜欢这里是我需要两个单独的语句来构造 ATL :: CComBSTR
绑定到转换结果。
what I don't like here is that I need two separate statements to just construct the ATL::CComBSTR
bound to the convertion result.
有更好的方法来完成同样的任务吗?
Is there a better way to accomplish the same task?
推荐答案
CComBSTR
已重载 char * code>和
wchar_t *
,它们代表您调用 SysAllocString()
。所以在你的代码片段中的显式分配实际上是不必要的。以下代码也可以工作:
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);
此外,如果您不需要使用转换的 BSTR
你的代码中的其他地方,你可以在方法调用中就地执行对象构造,像这样:
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));
同样适用于 _bstr_t
如果您不想要对ATL的依赖,可以使用 CComBSTR
代替
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.
这篇关于如何最好地将CString转换为BSTR,将其作为“in”参数放入COM方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!