1 std::string ConvertBSTRToMBS(BSTR bstr) 2 { 3 int wslen = ::SysStringLen(bstr); 4 return ConvertWCSToMBS((wchar_t*)bstr, wslen); 5 } 6 7 std::string ConvertWCSToMBS(const wchar_t* pstr, long wslen) 8 { 9 int len = ::WideCharToMultiByte(CP_ACP, 0, pstr, wslen, NULL, 0, NULL, NULL); 10 11 std::string dblstr(len, '\0'); 12 len = ::WideCharToMultiByte(CP_ACP, 0 /* no flags */, 13 pstr, wslen /* not necessary NULL-terminated */, 14 &dblstr[0], len, 15 NULL, NULL /* no default char */); 16 17 return dblstr; 18 } 19 20 BSTR ConvertMBSToBSTR(const std::string& str) 21 { 22 int wslen = ::MultiByteToWideChar(CP_ACP, 0 /* no flags */, 23 str.data(), str.length(), 24 NULL, 0); 25 26 BSTR wsdata = ::SysAllocStringLen(NULL, wslen); 27 ::MultiByteToWideChar(CP_ACP, 0 /* no flags */, 28 str.data(), str.length(), 29 wsdata, wslen); 30 return wsdata; 31 }
1 // given BSTR bs 2 assert(bs != nullptr); 3 std::wstring ws(bs, SysStringLen(bs));
1 // given std::wstring ws 2 assert(!ws.empty()); 3 BSTR bs = SysAllocStringLen(ws.data(), ws.size());
1 #include <comdef.h> 2 3 BSTR bs = SysAllocString("Hello"); 4 std::wstring myString = _bstr_t(bs, false); // will take over ownership, so no need to free