title: BSTR to std::string (std::wstring) and vice versa
body: <p>While working with COM in C++ the strings are usually of <code>BSTR</code> data type. Someone can use <code>BSTR</code> wrapper like <code>CComBSTR</code> or MS's <code>CString</code>. But because I can't use ATL or MFC in MinGW compiler, is there standard code snippet to convert <code>BSTR</code> to <code>std::string</code> (or <code>std::wstring</code>) and vice versa? </p>
  
  <p>Are there also some non-MS wrappers for <code>BSTR</code> similar to <code>CComBSTR</code>?</p>
  
  <h2>Update</h2>
  
  <p>Thanks to everyone who helped me out in any way! Just because no one has addressed the issue on conversion between <code>BSTR</code> and <code>std::string</code>, I would like to provide here some clues on how to do it.</p>
  
  <p>Below are the functions I use to convert <code>BSTR</code> to <code>std::string</code> and <code>std::string</code> to <code>BSTR</code> respectively:</p>
  
  <pre><code>std::string ConvertBSTRToMBS(BSTR bstr)
  {
      int wslen = ::SysStringLen(bstr);
      return ConvertWCSToMBS((wchar_t*)bstr, wslen);
  }
  
  std::string ConvertWCSToMBS(const wchar_t* pstr, long wslen)
  {
      int len = ::WideCharToMultiByte(CP_ACP, 0, pstr, wslen, NULL, 0, NULL, NULL);
  
      std::string dblstr(len, '\0');
      len = ::WideCharToMultiByte(CP_ACP, 0 /* no flags */,
                                  pstr, wslen /* not necessary NULL-terminated */,
                                  &amp;dblstr[0], len,
                                  NULL, NULL /* no default char */);
  
      return dblstr;
  }
  
  BSTR ConvertMBSToBSTR(const std::string&amp; str)
  {
      int wslen = ::MultiByteToWideChar(CP_ACP, 0 /* no flags */,
                                        str.data(), str.length(),
                                        NULL, 0);
  
      BSTR wsdata = ::SysAllocStringLen(NULL, wslen);
      ::MultiByteToWideChar(CP_ACP, 0 /* no flags */,
                            str.data(), str.length(),
                            wsdata, wslen);
      return wsdata;
  }
  </code></pre>