C++ 将 BSTR 转换为 const char*
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4302364/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
convert BSTR to const char*
提问by subs
Possible Duplicates:
Which is better code for converting BSTR parameters to ANSI in C/C++?
How to convert char * to BSTR?
可能的重复:
哪个是在 C/C++ 中将 BSTR 参数转换为 ANSI 的更好代码?
如何将 char * 转换为 BSTR?
Hi guys, I am very new to C++, any one have any idea how i can convert BSTR to const char*?
大家好,我对 C++ 很陌生,有人知道如何将 BSTR 转换为 const char* 吗?
采纳答案by Nate
A BSTR
is actually a WCHAR*
with a length prefix. The BSTR
value points to the beginning of the string, not to the length prefix (which is stored in the bytes just “before” the location pointed to by the BSTR
).
ABSTR
实际上是WCHAR*
带有长度前缀的 a 。该BSTR
值指向字符串的开头,而不是长度前缀(它存储在 指向的位置“之前”的字节中BSTR
)。
In other words, you can treat a BSTR
as though it is a const WCHAR*
. No conversion necessary.
换句话说,您可以将 aBSTR
视为 a const WCHAR*
。无需转换。
So your question is really: “How can I convert a Unicode string (WCHAR*
) to a char*
?” and the answer is to use the ::WideCharToMultiByte
API function as explained here. Or, if you are using MFC/ATL in your application, use the ATL and MFC Conversion Macros.
所以你的问题真的是:“我怎样才能将 Unicode 字符串 ( WCHAR*
) 转换为char*
?” 答案是使用此处::WideCharToMultiByte
解释的API 函数。或者,如果您在应用程序中使用 MFC/ATL,请使用ATL 和 MFC 转换宏。
回答by Steve Townsend
回答by Jookia
typedef OLECHAR FAR * BSTR;
typedef WCHAR OLECHAR;
From here.
从这里开始。
WCHAR*. It's a wide char, not a char. This means it's Unicode, not ASCII and shouldn't be converted. If you want to use const char*, don't use wide types.
WCHAR*。这是一个宽字符,而不是一个字符。这意味着它是 Unicode,而不是 ASCII,不应进行转换。如果要使用 const char*,请不要使用宽类型。
Although, it is possible using some hackery, you'd possibly lose data as you'll be converting the text from Unicode to ASCII.
虽然可以使用一些hackery,但您可能会丢失数据,因为您会将文本从Unicode 转换为ASCII。