在我的新工作中,我们不使用 MFC - 但幸运的是 std lib 和 C++11 - 所以我遇到了与 c00000fd 相同的问题。感谢 BitTickler 的回答,我想出了通过 Win32-API 使用字符串内部缓冲区的想法&s[0]
resp. &s.front()
catch.
使用 Win32-API 函数shrinks内部字符串缓冲区
假设您有一个字符串,该字符串将被 Win32-API 函数缩短 - 例如::PathRemoveFileSpec(path)
- 您可以遵循以下方法:
std::string path( R("?(C:\TESTING\toBeCutOff)?") );
::PathRemoveFileSpec( &path.front() ); // Using the Win32-API
// and the the string's internal buffer
path.resize( strlen( path.data() ) ); // adjust the string's length
// to the first \0 character
path.shrink_to_fit(); // optional to adjust the string's
// capacity - useful if you
// do not plan to modify the string again
统一码版本:
std::wstring path( LR("?(C:\TESTING\toBeCutOff)?") );
::PathRemoveFileSpec( &path.front() ); // Using the Win32-API
// and the the string's internal buffer
path.resize( wcslen( path.data() ) ); // adjust the string's length
// to the first \0 character
path.shrink_to_fit(); // optional to adjust the string's
// capacity - useful if you
// do not plan to modify the string again
使用 Win32-API 函数extends内部字符串缓冲区
假设您有一个字符串,该字符串将由 Win32-API 函数扩展或填充 - 例如::GetModuleFileName(NULL, path, cPath)
要检索可执行文件的路径 - 您可以遵循以下方法:
std::string path;
path.resize(MAX_PATH); // adjust the internal buffer's size
// to the expected (max) size of the
// output-buffer of the Win32-API function
::GetModuleFileName( NULL, &path.front(), static_cast<DWORD>( path.size() ) );
// Using the Win32-API
// and the the string's internal buffer
path.resize( strlen( path.data() ) ); // adjust the string's length
// to the first \0 character
path.shrink_to_fit(); // optional to adjust the string's
// capacity - useful if you
// do not plan to modify the string again
统一码版本:
std::wstring path;
path.resize(MAX_PATH); // adjust the internal buffer's size
// to the expected (max) size of the
// output-buffer of the Win32-API function
::GetModuleFileName( NULL, &path.front(), static_cast<DWORD>( path.size() ) );
// Using the Win32-API
// and the the string's internal buffer
path.resize( wcslen( path.data() ) ); // adjust the string's length
// to the first \0 character
path.shrink_to_fit(); // optional to adjust the string's
// capacity - useful if you
// do not plan to modify the string again
当您最终收缩以适应字符串时,与 MFC 替代方案相比,扩展字符串的内部缓冲区时只需要多一行代码,而收缩字符串时它的开销几乎相同。
的优点std::string
与此相反的方法CString
方法是你不必声明额外的 C-String 指针变量,你只需使用官方的std::string
方法和一种strlen
/wcslen
功能。
上面显示的方法仅适用于当生成的 Win32-API 缓冲区以 null 终止时的收缩变体,但对于 Win32-API 返回未终止字符串的非常特殊的情况,那么 - 类似于CString::ReleaseBuffer
方法 - 您必须明确知道并指定新的字符串/缓冲区长度path.resize( newLength )
- 就像path.ReleaseBuffer( newLength )
为了CString
选择。