convert BSTR to const char* [duplicate]

匿名 (未验证) 提交于 2019-12-03 03:06:01

问题:

Possible Duplicates:
Which is better code for converting BSTR parameters to ANSI in C/C++?
How to convert char * to BSTR?

Hi guys, I am very new to C++, any one have any idea how i can convert BSTR to const char*?

回答1:

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).

In other words, you can treat a BSTR as though it is a const WCHAR*. No conversion necessary.

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.



回答2:

#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); 

This handles all the Wide Char to multibyte conversion.



回答3:

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.

Although, it is possible using some hackery, you'd possibly lose data as you'll be converting the text from Unicode to ASCII.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!