如何最好地将 CString 转换为 BSTR 以将其作为“in"传递?参数到 COM 方法? [英] How to best convert CString to BSTR to pass it as an "in" parameter into a COM method?

查看:20
本文介绍了如何最好地将 CString 转换为 BSTR 以将其作为“in"传递?参数到 COM 方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将 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*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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆