C++: Convert wchar_t* to BSTR?(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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C++:将 wchar_t* 转换为 BSTR?
基础教程推荐
- C++:获取传递给函数的多维数组的行大小 2021-01-01
- 如何更改 SysDateTimePick32 或 CDateTimeCtrl 的背景颜色? 2022-01-01
- 提升 ASIO 流缓冲 2021-01-01
- 随机插入/删除的综合向量与链表基准 2022-01-01
- 将不可复制的闭包对象传递给 std::function 参数 2021-01-01
- 如何部分禁用 cmake C/C++ 自定义编译器检查 2021-01-01
- 如何在 C++ 中正确使用命名空间? 2022-01-01
- 与 CAS 的原子交换(使用 gcc 同步内置函数) 2022-01-01
- 为什么我们不能使用“虚拟继承"?在 COM 中? 2022-01-01
- c++ STL设置差异 2022-01-01
