1

I am new to _bstr_t's and still trying to get the hang of it. I was trying to check whether a particular string x is contained anywhere within the bstring. Something I would normally do like;

String x = "hello";
String example = "You! hello there";
...
if (example.find(x) != string::npos) {
...

Just for the record the intended platform is windows.

pondigi
  • 856
  • 2
  • 8
  • 14

2 Answers2

4

There is no need to use _bstr_t. Use the BSTR type.

Next, read Eric's Complete Guide to BSTR Semantics.

Lastly, you can use the BSTR in native code the way you would a normal character array in most cases.

BSTR bstr = SysAllocString(L"FooBarBazQux");
if (wcsstr(bstr, L"Bar") != NULL) {
  // Found it! Do something.
} else {
  // Not there.
}
SysFreeString(bstr);

MSDN for wcsstr.

i_am_jorf
  • 53,608
  • 15
  • 131
  • 222
  • thanks for the help, however the compiler does not seem to like something, `error C2665: 'wcsstr' : none of the 2 overloads could convert all the argument types` ... `const wchar_t *wcsstr(const wchar_t *,const wchar_t *)` ... `wchar_t *wcsstr(wchar_t *,const wchar_t *)` – pondigi Oct 06 '11 at 16:14
  • Hard to say without seeing your code. Could be a `const` issue? You can always ask a new question with your new code. – i_am_jorf Oct 06 '11 at 16:18
  • 2
    Disagree with the first advice, `BSTR` is a recipe for memory leaks. Equivalent code: `_bstr_t bstr(L"FooBarBazQux"); if (wcsstr(bstr, L"Bar") != NULL) { } else { }`. No SysFreeString needed. – MSalters Oct 06 '11 at 22:34
  • 1
    At least use `CComBSTR` if you're going to make that argument. – i_am_jorf Oct 06 '11 at 22:56
1

Your example appears to be trying to use string::find from STL. But you specify your variables of type "String" (capitalized). If you instead did:

using namespace std;
string x = "hello";
string example = "You! hello there";
...

your example would compile. Do you actually have a BSTR or _bstr_t that you need to work with that you haven't shown? Even if so, it's pretty easy to make an std::string from a _bstr_t, and after that you can use STL as you normally would.