在我的新工作中,我們不使用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並在那裏瀏覽一段時間。 –