开发者

Is there an equivalent way to do CString::GetBuffer in std::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 st开发者_运维问答d::wstring)'s buffer directly?

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

Taworn T.


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.


use std::string::c_str() to retrieve a const char * that is null terminated. std::string::data() also returns a const char * but that may not be null terminated.

But like zeuxcg says, I dont suggest you to write directly in that buffer.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜