0

I am using Visual C++ 2008. In my code, I get a variable of BSTR. Now I want to change the first half of the characters in it. How to do so?

For example, if the string contains 5000 characters, then I want to modify the first 2500 characters in its buffer directly. Is there a easy way to do so?

I understand that I can convert BSTR to CString, or std::string, then do the replacement. But that will consume extra memory and time, especially when the string is very long. So I hope to modify the buffer of BSTR directly. That will be fast and efficient.

dbush
  • 205,898
  • 23
  • 218
  • 273
alancc
  • 487
  • 2
  • 24
  • 68
  • 4
    A `BSTR` is a `wchar_t*` pointer to the character data (there is metadata before the character data, but we can ignore that for now), so what is stopping you from modifying the characters directly as desired? And what does any of this have to do with `VARIANT`? If the `BSTR` is inside of a `VARIANT`, then simply access the `VARIANT`'s `bstrVal` or `pbstrVal` field to reach the `BSTR`, depending on whether or not the `VARIANT`'s `vt` field is set to `VT_BSTR` or `VT_BSTR|VT_BYREF`, respectively. – Remy Lebeau May 14 '21 at 02:25
  • @RemyLebeau, Thank yu very muchy. – alancc May 14 '21 at 22:03

1 Answers1

0

you dont need to convert anything and waste memory, use Attach/Detach

BSTR str;
CComBSTR wrapper;
wrapper.Attach(str);
// work with wrapper
wrapper.Detach();
Andrey
  • 1,752
  • 18
  • 17