我有std::list<std::wstring>
[0] = "abc"
[1] = "wds"
[2] = "rew"
[n] = ...
(永远不要将列表中的索引作为示例)
有没有简单的方法将它转换为经典的C字节数组,以便我可以使用winsocks send()
函数发送它?
答案 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());