10

我需要将CString实例转换为正确分配的实例并将其BSTR传递BSTR给 COM 方法。为了让代码能够为 ANSI 和 Unicode 编译和工作,我使用CString::AllocSysString()将任何格式转换CString为 Unicode BSTR。

由于没有人拥有返回的 BSTR,我需要处理它并在调用完成后以最安全的方式和尽可能少的代码释放它。

目前我ATL::CComBSTR用于生命周期管理:

 ATL::CComBSTR converted;
 converted.Attach( sourceString.AllocSysString() ); //simply attaches to BSTR, doesn't reallocate it
 interface->CallMethod( converted );

我在这里不喜欢的是我需要两个单独的语句来构造ATL::CComBSTR转换结果的绑定。

有没有更好的方法来完成相同的任务?

4

3 回答 3

17

CComBSTRchar*and重载了构造函数,它们代表您wchar_t*调用。SysAllocString()因此,您的代码片段中的显式分配实际上是不必要的。以下内容也可以:

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

此外,如果您不需要BSTR在代码中的其他地方使用转换后的内容,您可以在方法调用中就地执行对象构造,如下所示:

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

这同样适用于类,如果您不想依赖 ATL _bstr_t,可以使用它来代替。CComBSTR

于 2010-01-18T15:43:58.613 回答
2

One of the confusing aspects of Windows programming is managing the conversion of Visual Basic style strings to/from C language style strings. It isn't that it is so difficult, it is just difficult to remember the details. It is usually not done often, and the MSDN documentation is so voluminous that it is difficult to find answers to your questions. But, the worst part is that you could perform some typecast that compiles fine, but doesn't work the way you expect. This results in code that doesn't work, and the bugs are hard to track down. After some experience, you learn to make sure your string conversions are doing what you expect.

C strings are arrays of characters terminated by a NULL character. Visual Basic strings differ in that the length of the string precede the characters in the string. So, a VB string knows its own length. In addition, all VB strings are Unicode (16 bits per character). String Types

BSTR/C String conversions are required if:

You are doing COM programming in C/C++
You are writing multiple language applications, such as C++ DLL's accessed by Visual Basic applications.
于 2012-02-08T19:02:25.807 回答
2

构造函数之一_bstr_t允许您简单地附加到现有的BSTR,以便您可以CString::AllocSysStringBSTR分配失败时获得所需的异常。

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

构造_bstr_t函数文档说:

_bstr_t(
   BSTR bstr,
   bool fCopy 
);

fCopy
如果为 false,则将bstr参数附加到新对象而不通过调用复制SysAllocString

另一方面,CComBSTR构造函数似乎没有相应的签名;BSTR虽然如果不是真的需要分配失败异常,也可以使用它,正如Phil Booth他的回答中提到的那样。

于 2013-01-23T02:17:35.163 回答