How would you convert a std::string to BSTR*?

xkm picture xkm · Jul 9, 2015 · Viewed 16.3k times · Source

How would you convert a std::string to BSTR*?

STDMETHODIMP CMyRESTApp::rest(BSTR data, BSTR* restr)
{
    RESTClient restclient;
    RESTClient::response resp = restclient.get(data);

    Log("Response Status code: %s", resp.code);
    Log("Response Body: %s", resp.body);

    *restr = // here
    return S_OK;
}

I need convert the resp.body and this then to be returned for the *restr here.

Answer

Niall picture Niall · Jul 9, 2015

An ATL based approach is to use ATL::CComBSTR and then a Detach() (or CopyTo(...)) the resultant CComBSTR to the BSTR*

Something like:

CComBSTR temp(stlstr.c_str());
*restr = temp.Detach();

Else in general for std::basic_string you can use the Win32 API Sys* family of functions, such as SysAllocStringByteLen and SysAllocString;

// For the `const char*` data type (`LPCSTR`);
*restr = SysAllocStringByteLen(stlstr.c_str(), stlstr.size());

// More suitable for OLECHAR
*restr = SysAllocString(stlwstr.c_str());

OLECHAR depends on the target platform, but generally it is wchar_t.

Given your code, the shortest snippet could just be;

*restr = SysAllocStringByteLen(resp.body.c_str(), resp.body.size());

Note these Windows API functions use the "usual" windows code page conversions, please see further MSDN documentation on how to control this if required.