C++:将 wchar_t* 转换为 BSTR? [英] C++: Convert wchar_t* to BSTR?

查看:68
本文介绍了C++:将 wchar_t* 转换为 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.

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

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