如何将 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
How to compare BSTR against a string in c/c++?
提问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 wcscmp
instead:
你必须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 wcscmp
will 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_t
wrappers 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 {
//...