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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 15:04:16  来源:igfitidea点击:

convert BSTR to const char*

c++

提问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 BSTRis actually a WCHAR*with a length prefix. The BSTRvalue 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 BSTRas 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 ::WideCharToMultiByteAPI 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

#include "comutil.h"

BSTR bstrVal;
_bstr_t interim(bstrVal, false);    
    // or use true to get original BSTR released through wrapper
const char* strValue((const char*) bstrVal);

Thishandles all the Wide Char to multibyte conversion.

这将处理所有宽字符到多字节的转换。

回答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。