Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an equivalent way to do CString::GetBuffer in std::string?

Tags:

c++

string

Many Windows API, such as GetModuleFileName, etc... write output to char* buffer. But it is more convenient to use std::string. Is there a way to have them write to std::string (or std::wstring)'s buffer directly?

Sorry for my poor English. I'm not a native English speaker. -_-

Taworn T.

like image 576
Tpig Avatar asked Mar 21 '26 05:03

Tpig


1 Answers

If you're using C++0x, then the following is guaranteed to work:

std::string s;
s.resize(max_length);
size_t actual_length = SomeApiCall(&s[0], max_length);
s.resize(actual_length);

Before C++0x the std::string contents is not guaranteed to be consecutive in memory, so the code is not reliable in theory; in practice it works for popular STL implementations.

like image 106
zeuxcg Avatar answered Mar 23 '26 17:03

zeuxcg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!