本文介绍了C ++:将wchar_t *转换为BSTR?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图将 wchar_t * 转换为 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);

A 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样式类(或者甚至微软的 _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.

这篇关于C ++:将wchar_t *转换为BSTR?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-22 20:56