BSTR para std :: string (std :: wstring) e vice-versa
Enquanto trabalha com COM em C ++, as strings geralmente são deBSTR
tipo de dados. Alguém pode usarBSTR
wrapper likeCComBSTR
ou MS'sCString
. Mas como não posso usar ATL ou MFC no compilador MinGW, há um trecho de código padrão para converterBSTR
parastd::string
(oustd::wstring
) e vice versa
Há também alguns invólucros que não são da MS paraBSTR
igual aCComBSTR
?
Obrigado a todos que me ajudaram de alguma forma! Só porque ninguém abordou o problema de conversão entreBSTR
estd::string
, Gostaria de fornecer aqui algumas dicas sobre como fazê-l
Abaixo estão as funções que eu uso para converterBSTR
parastd::string
estd::string
paraBSTR
respectivamente:
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 */,
&dblstr[0], len,
NULL, NULL /* no default char */);
return dblstr;
}
BSTR ConvertMBSToBSTR(const std::string& 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;
}