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

你说的曾经没有我的故事 提交于 2019-11-30 23:21:01

问题


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 *'

回答1:


You have to use wcscmp instead:

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.

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




回答2:


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




回答3:


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

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



回答4:


My solution:

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


来源:https://stackoverflow.com/questions/3700772/how-to-compare-bstr-against-a-string-in-c-c

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