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?


基础教程推荐
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 从 std::cin 读取密码 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01