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

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

Convert BSTR to char*

c++visual-c++charbstr

提问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. ConvertBSTRToStringdoes just that. As for the strcpy, testDestneeds 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 BSTRdocumentation on MSDN):

不过有几个警告(正如您从BSTRMSDN 上的文档中看到的那样):

  • 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 strcpymay notalways work as expected.

因此,您strcpy可能并不总是按预期工作。