Export (0) Print
Expand All

_bstr_t::Assign

Microsoft Specific

Copies a BSTR into the BSTR wrapped by a _bstr_t.

void Assign(
   BSTR s
);

Parameters

s
A BSTR to be copied into the BSTR wrapped by a _bstr_t.

Remarks

Assign does a binary copy, which means the entire length of the BSTR is copied, regardless of content.

Example

// _bstr_t_Assign.cpp
#include <comdef.h>
#include <stdio.h>
int main()
{
   _bstr_t bstrWrapper;   // creates a _bstr_t wrapper
   bstrWrapper = "some text";   // creates BSTR and attaches to it
   wprintf(L"bstrWrapper = %s\n", static_cast<wchar_t*>(bstrWrapper));

   BSTR bstr = bstrWrapper.Detach();   // bstrWrapper releases its BSTR
   wprintf(L"bstrWrapper = %s\n", static_cast<wchar_t*>(bstrWrapper));
   wprintf(L"bstr = %s\n", bstr);   // "some text" 

   bstrWrapper.Attach(SysAllocString(OLESTR("SysAllocedString")));
   wprintf(L"bstrWrapper = %s\n", static_cast<wchar_t*>(bstrWrapper));

   bstrWrapper.Assign(bstr);   // assign a BSTR to our _bstr_t
   wprintf(L"bstrWrapper = %s\n", static_cast<wchar_t*>(bstrWrapper));

   SysFreeString(bstr);   // done with BSTR, do manual cleanup

   bstr= SysAllocString(OLESTR("Yet another string"));   // resuse bstr
   _bstr_t bstrWrapper2 = bstrWrapper;   // two wrappers, one BSTR 

   *bstrWrapper.GetAddress() = bstr;
   bstr = 0;   // bstrWrapper and bstrWrapper2 do still point to BSTR
   wprintf(L"bstrWrapper = %s\n", static_cast<wchar_t*>(bstrWrapper));
   wprintf(L"bstrWrapper2 = %s\n", static_cast<wchar_t*>(bstrWrapper2));

   _snwprintf(bstrWrapper.GetBSTR(), bstrWrapper.length(), L"changing BSTR");   // new value into BSTR
   wprintf(L"bstrWrapper = %s\n", static_cast<wchar_t*>(bstrWrapper));
   wprintf(L"bstrWrapper2 = %s\n", static_cast<wchar_t*>(bstrWrapper2));
}

Output

bstrWrapper = some text
bstrWrapper = (null)
bstr = some text
bstrWrapper = SysAllocedString
bstrWrapper = some text
bstrWrapper = Yet another string
bstrWrapper2 = some text
bstrWrapper = changing BSTR
bstrWrapper2 = some text

END Microsoft Specific

See Also

_bstr_t Class

Show:
© 2014 Microsoft