Thursday, October 1, 2015

Conversion of wstring to PWSTR

Common examples
std::string s = SOME_STRING; // get temporary LPSTR (not really safe) LPSTR pst = &s[0]; // get temporary LPCSTR (pretty safe) LPCSTR pcstr = s.c_str(); // convert to std::wstring std::wstring ws; ws.assign( s.begin(), s.end() ); // get temporary LPWSTR (not really safe) LPWSTR pwst = &ws[0]; // get temporary LPCWSTR (pretty safe) LPCWSTR pcwstr = ws.c_str();


Solved problem:
Create( __in SomeMap &Metrics, __out PWSTR *metric ) { std::wstring *current = NULL; try { current = new std::wstring(); for (iterator iterator = Metrics.begin(); iterator != Metrics.end(); iterator++) { if (!current->empty()) { current->append (L";"); } current->append(L"{"); current->append(iterator->first.begin(), iterator->first.end()); current->append(L":"); current->append(iterator->second.begin(), iterator->second.end()); current->append(L"}"); } //Either of the following can be used. for the first one, it is directly converting wstring to PWSTR. //second one is using c_str() which converts first to PCWSTR. and then to PWSTR // Since it is first converting to PCWSTR, if we want to change the value later on of the *metric, it will cause memory corruption //*metric = &(*current)[0]; //*metric = const_cast<PWSTR> (current->c_str()); } catch (...) { } Cleanup: if (*metric == NULL) { PTR_FREE(current); } }

No comments:

Post a Comment