将字符串列表转换为C样式数组

时间:2014-10-31 19:13:50

标签: c++ arrays list winsock

我有std::list<std::wstring>

[0] = "abc"
[1] = "wds"
[2] = "rew"
[n] = ...

(永远不要将列表中的索引作为示例)

有没有简单的方法将它转换为经典的C字节数组,以便我可以使用winsocks send()函数发送它?

1 个答案:

答案 0 :(得分:2)

警告:我没有编译过这个。但它应该给你这个想法。基本上你只需要创建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());
相关问题