在我的新工作中,我们不使用MFC--但幸运的是std lib和C++ 11--所以我已经遇到与c00000fd相同的问题。感谢BitTickler的回答,我提出了通过&s[0]
或其他方法使用字符串内部缓冲区来实现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替代方法相比时,缩小字符串时它具有几乎相同的开销。
在对比的是CString
方法的std::string
方法的优点是,你不必声明一个额外的C字符串指针变量,你只是与官方std::string
方法的工作原理和strlen
/wcslen
功能。 上面显示的我的方法只适用于收到的Win32-API缓冲区为空终止的变体,但对于Win32-API返回未终止字符串的特殊情况,则 - 类似于CString::ReleaseBuffer
方法 - 必须明确知道并指定新的字符串/缓冲区长度path.resize(newLength)
- 就像path.ReleaseBuffer(newLength)
替代CString
。
你*不*。如果你需要修改字符串,你可以修改字符串。如果您将字符串传递给采用常量字符指针的旧函数,则只需要“C缓冲区”。 –
@JoachimPileborg:好的,假设'CharLower' API不是'CharLower',而是一些任意的API,它会修改我需要从'std :: string'获取的输入缓冲区。我会怎么做?这就是我要问的。 – c00000fd
我告诉你,你不需要*原始缓冲区,你需要的所有东西都已经在字符串类或标准库中。看看例如http://en.cppreference.com/w/cpp并在那里浏览一段时间。 –