如何将std :: string与采用char []缓冲区的Win32函数混合使用?

Lee*_*aks 7 c++ string winapi stl

有许多Win32函数接受缓冲区的地址,例如TCHAR[256],并将一些数据写入该缓冲区.它可能小于缓冲区的大小,也可能是整个缓冲区.

通常你会在循环中调用它,例如从流或管道中读取数据.最后,我想有效地返回一个字符串,该字符串包含来自所有迭代调用的完整数据,以检索此数据.我一直在考虑使用,std::string因为它的+ =以类似于Java或C#StringBuffer.append()/ StringBuilder.Append()方法的方式进行优化,有利于速度而不是内存.

但是我不确定如何最好地std::string与Win32函数混合使用,因为这些函数都是char[]从头开始的.有什么建议?

Dmi*_*try 11

如果参数是输入 - 仅使用std::string这样

std::string text("Hello");
w32function(text.c_str());
Run Code Online (Sandbox Code Playgroud)

如果参数是输入/输出,请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]);
Run Code Online (Sandbox Code Playgroud)

如果参数是输出 - 仅使用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
Run Code Online (Sandbox Code Playgroud)

你也可以使用std::basic_string<TCHAR>,std::vector<TCHAR>如果需要的话.

您可以在Scott Meyers 的" 有效STL "一书中阅读有关该主题的更多信息.


Bri*_*ndy 6

而不是std :: string,我建议使用std::vector,并在使用&v.front()时使用v.size().确保已经分配了空间!

你必须小心std::string和二进制数据.

s += buf;//will treat buf as a null terminated string
s += std::string(buf, size);//would work
Run Code Online (Sandbox Code Playgroud)


mis*_*tor 6

std::string有一个c_str()返回其等效C风格字符串的函数.(const char *)

此外,std::string重载的赋值运算符将C样式的字符串作为输入.

例如,ss设为std::string实例并sc成为C风格的字符串,然后可以执行相互转换:

ss = sc; // from C-style string to std::string
sc = ss.c_str(); // from std::string to C-style string
Run Code Online (Sandbox Code Playgroud)

更新:

正如迈克韦勒所指出的那样,如果UNICODE定义了宏,那么字符串将是wchar_t*,因此你将不得不使用std::wstring.

  • 使用std :: string作为内存缓冲区是不正确的,因为当前标准不保证它在内存中是连续的. (2认同)