有许多 Win32 函数获取缓冲区的地址,例如 TCHAR[256]
,并将一些数据写入该缓冲区。它可能小于缓冲区的大小,也可能是整个缓冲区。
您通常会在循环中调用它,例如从流或管道中读取数据。最后,我想有效地返回一个字符串,该字符串具有来自所有迭代调用的完整数据以检索此数据。我一直在考虑使用 std::string
,因为它的 += 以类似于 Java 或 C# 的 StringBuffer.append()
/StringBuilder.Append 的方式进行了优化()
方法,有利于速度而不是内存。
但我不确定如何最好地将 std::string
与 Win32 函数混合在一起,因为这些函数以 char[]
开头。有什么建议吗?
最佳答案
如果参数是input-only 使用std::string
像这样
std::string text("Hello");
w32function(text.c_str());
如果参数是输入/输出,使用std::vector<char>
而是像这样:
std::string input("input");
std::vector<char> input_vec(input.begin(), input.end());
input_vec.push_back('\0');
w32function(&input_vec[0], input_vec.size());
// Now, if you want std::string again, just make one from that vector:
std::string output(&input_vec[0]);
如果参数是仅输出也使用std::vector<Type>
像这样:
// allocates _at least_ 1k and sets those to 0
std::vector<unsigned char> buffer(1024, 0);
w32function(&buffer[0], buffer.size());
// use 'buffer' vector now as you see fit
您还可以使用 std::basic_string<TCHAR>
和 std::vector<TCHAR>
如果需要的话。
您可以在 Scott Meyers 所著的 Effective STL 一书中阅读有关该主题的更多信息。
关于c++ - 如何将 std::string 与采用 char[] 缓冲区的 Win32 函数混合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2057946/