我有一个 std::list<std::wstring>
[0] = "abc"
[1] = "wds"
[2] = "rew"
[n] = ...
(不要在意列表中的索引,它只是为了示例)
有什么简单的方法可以将它转换成经典的 C 字节数组,以便我可以使用 winsocks 发送它 send()
功能?
最佳答案
警告:我没有编译这个。但它应该给你这个想法。基本上,您只需创建 C 样式数组并将每个字符串中的数据附加到其中:
std::vector<wchar_t> cArray;
// Optional: Calculate the length of the desired byte array in advance
std::size_t actualSize = 1 + strings.size(); // stringLengths + number of strings + 1
for (std::wstring const& source : strings)
{
actualSize += source.size();
}
cArray.reserve(actualSize);
// End optional bits
for (std::wstring const& source : strings)
{
cArray.insert(cArray.end(), source.begin(), source.end());
cArray.push_back(L'\0'); // null terminate
}
// double null terminate?
cArray.push_back(L'\0');
char const* cByteArray = reinterpret_cast<char const*>(cArray.data());
关于c++ - 将字符串列表转换为 C 样式数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26681870/