C++ 将 BSTR 转换为字符*
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3648848/
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 char*
提问by barlyee
Anyone know how to convert BSTR to char* ?
有人知道如何将 BSTR 转换为 char* 吗?
Update: I tried to do this, but don't know if it is right or wrong.
更新:我尝试这样做,但不知道它是对还是错。
char *p= _com_util::ConvertBSTRToString(URL->bstrVal);
strcpy(testDest,p );
回答by dirkgently
Your code is okay. ConvertBSTRToString
does just that. As for the strcpy
, testDest
needs to be large enough to hold the string pointed to by p
. Note that since ConvertBSTRToString allocates a new string you will need to free it somewhere down the line. Once you are done make sure you do:
你的代码没问题。ConvertBSTRToString
就是这样。至于strcpy
,testDest
需要足够大以容纳 指向的字符串p
。请注意,由于 ConvertBSTRToString 分配了一个新字符串,因此您需要在该行的某处释放它。完成后,请确保您执行以下操作:
delete[] p;
A couple of caveats though (as you can see from BSTR
documentation on MSDN):
不过有几个警告(正如您从BSTR
MSDN 上的文档中看到的那样):
- On Microsoft Windows, consists of a string of Unicode characters (wide or double-byte characters).
- May contain multiple embedded null characters.
- 在 Microsoft Windows 上,由一串 Unicode 字符(宽或双字节字符)组成。
- 可能包含多个嵌入的空字符。
So, your strcpy
may notalways work as expected.
因此,您strcpy
可能并不总是按预期工作。