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?


- 使用/clr 时出现 LNK2022 错误 2022-01-01
- 从python回调到c++的选项 2022-11-16
- 近似搜索的工作原理 2021-01-01
- C++ 协变模板 2021-01-01
- 静态初始化顺序失败 2022-01-01
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
- Stroustrup 的 Simple_window.h 2022-01-01
- 如何对自定义类的向量使用std::find()? 2022-11-07
- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
- STL 中有 dereference_iterator 吗? 2022-01-01