如何将 BSTR 与 c/c++ 中的字符串进行比较?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3700772/
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:31:22  来源:igfitidea点击:

How to compare BSTR against a string in c/c++?

c++windowscomactivex

提问by COMer

wprintf(L"Selecting Audio Input Device: %s\n", 
                            varName.bstrVal);

if(0 == strcmp(varName.bstrVal, "IP Camera [JPEG/MJPEG]"))...

The above reports :

以上报道:

error C2664: 'strcmp' : cannot convert parameter 1 from 'BSTR' to 'const char *'

回答by Brian R. Bondy

You have to use wcscmpinstead:

你必须wcscmp改用:

if(0 == wcscmp(varName.bstrVal, L"IP Camera [JPEG/MJPEG]"))
{
}

Here is a description of the BSTR data type, it has a length prefix and a real string part which is just an array of WCHAR characters. It also has 2 NULL terminators.

这里是BSTR 数据类型描述,它有一个长度前缀和一个真正的字符串部分,它只是一个 WCHAR 字符数组。它还有 2 个 NULL 终止符。

The only thing to look out for is that the BSTR data type can contain embedded NULLs in the string portion, so wcscmpwill only work in the cases where the BSTR does not contain embedded NULLs (which is probably most cases).

唯一需要注意的是,BSTR 数据类型可以在字符串部分包含嵌入的 NULL,因此wcscmp仅适用于 BSTR 不包含嵌入的 NULL 的情况(这可能是大多数情况)。

回答by Steve Townsend

As a richer alternative to the C runtime, you could use the Unicode CompareString or CompareStringExAPIs in Win32. If you don't have charset issues to consider, wcscmp is fine though.

作为 C 运行时的更丰富的替代方案,您可以在 Win32 中使用 Unicode CompareString 或CompareStringExAPI。如果您没有要考虑的字符集问题,那么 wcscmp 就可以了。

回答by Pedro d'Aquino

I always construct _bstr_twrappers around BSTRs. It makes things quite a bit easier and more idiomatic:

我总是_bstr_t围绕 BSTR构建包装器。它使事情变得更容易和更惯用:

if(std::string("IP Camera [JPEG/MJPEG]") ==
                   static_cast<const char*>( _bstr_t(varName.bstrVal) )
{
}

回答by MSalters

My solution:

我的解决方案:

static const std::wstring IPCamera = L"IP Camera [JPEG/MJPEG]";
if (varName.bstrVal == IPCamera {
  //...