MFC String: How to convert between a 'CString' and a 'BSTR'?
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3

Thread: MFC String: How to convert between a 'CString' and a 'BSTR'?

Threaded View

  1. #1
    Join Date
    Jun 2001
    Location
    Switzerland
    Posts
    4,443

    MFC String: How to convert between a 'CString' and a 'BSTR'?

    Q: How to convert between a 'CString' and a 'BSTR'?

    A:

    'CString' to 'BSTR':

    Use the AllocSysString member function of the CString:

    Code:
    CString cs("Hello");
    BSTR bstr = cs.AllocSysString();
    If you pass the 'BSTR' to some OLE function, this will normally free the 'BSTR' memory when done with it.

    If you use the 'BSTR' by yourself, dont forget to call '::SysFreeString()' when you're done with it.

    Code:
    ::SysFreeString(bstr);
    'BSTR' to 'CString':

    You will mostly need this when you have some OLE function that returns a 'BSTR'. Such an OLE Function will basically do something like this:

    Code:
    HRESULT SomeOLEFunction(BSTR& bstr)
    {
      bstr = ::SysAllocString(L"Hello");
      return S_OK;
    }
    Use a temporary variable of the type '_bstr_t' to wrap the 'BSTR'. This way you handle both the 208 and make sure that you have no memory leak:
    Code:
    BSTR bstr;
    SomeOLEFunction(bstr);
    _bstr_t tmp(bstr, FALSE);   //wrap the BSTR
    CString cs(static_cast<const char*>(tmp));  //convert it
    AfxMessageBox(cs, MB_OK, 0);
    // when tmp goes out of scope it will free the BSTRs memory
    Note, that this won't work in a UNICODE build.


    Last edited by Andreas Masur; July 24th, 2005 at 07:48 AM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Windows Mobile Development Center


Click Here to Expand Forum to Full Width

This is a CodeGuru survey question.


Featured


HTML5 Development Center