C++:将 wchar_t* 转换为 BSTR?

2022-01-14 00:00:00 string com c++ bstr

我正在尝试将 wchar_t * 转换为 BSTR.

I'm trying to convert a wchar_t * to BSTR.

#include <iostream>
#include <atlstr.h>

using namespace std;

int main()
{
    wchar_t* pwsz = L"foo"; 

    BSTR bstr(pwsz);

    cout << SysStringLen(bstr) << endl;

    getchar();
}

这会打印出 0,这比我希望的要少.进行这种转换的正确方法是什么?

This prints 0, which is less than what I'd hoped. What is the correct way to do this conversion?

推荐答案

你需要使用 SysAllocString(然后是 SysFreeString).

You need to use SysAllocString (and then SysFreeString).

BSTR bstr = SysAllocString(pwsz);

// ...

SysFreeString(bstr);

BSTR 是一个托管字符串,字符串中的字符以其长度为前缀.SysAllocString 分配正确的存储量并正确设置字符串的长度和内容.BSTR 正确初始化后,SysStringLen 应该返回正确的长度.

A BSTR is a managed string with the characters of the string prefixed by their length. SysAllocString allocates the correct amount of storage and set up the length and contents of the string correctly. With the BSTR correctly initialized, SysStringLen should return the correct length.

如果您使用 C++,您可能需要考虑使用 RAII 样式类(甚至是 Microsoft 的 _bstr_t),以确保不会忘记任何 SysFreeString 调用.

If you're using C++ you might want to consider using a RAII style class (or even Microsoft's _bstr_t) to ensure that you don't forget any SysFreeString calls.

相关文章