在我的新工作中,我们不使用 MFC - 但幸运的是 std lib 和 C++11 - 所以我提出了与 c00000fd 相同的问题。感谢 BitTickler 的回答,我想出了通过 &s[0] resp 将字符串的内部缓冲区用于 Win32-API 的想法。 &s.front()抓住。
使用收缩内部字符串缓冲区的 Win32-API 函数
假设您有一个字符串,该字符串将被 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
Unicode 版本:
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 函数
假设您有一个字符串,该字符串将被 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
Unicode 版本:
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 方法和一个 @987654332 @/wcslen 函数。
我上面显示的方法仅适用于结果 Win32-API 缓冲区为空终止时的缩小变体,但对于 Win32-API 返回未终止字符串的非常特殊的情况,然后 - 类似于 CString::ReleaseBuffer 方法 - 你必须通过path.resize( newLength ) 明确知道并指定新的字符串/缓冲区长度——就像path.ReleaseBuffer( newLength ) 的CString 替代方案一样。