【发布时间】:2017-12-01 22:21:24
【问题描述】:
我想用一个未知的结构创建一个字节数组,并在这个字节数组的前面额外添加一个数字。我该怎么做?
我目前有这个代码:
template <class T>
void CopterConnection::infoToByteArray(char *&bit_data, size_t *msglen,
T data) {
// Determine which kind of element is in the array, will change in the final code
char typeID = -1;
*msglen = sizeof(data);
*msglen += 1; // take in account of typeID
// Create the pointer to the byte representation of the struct
bit_data = new char[*msglen];
// copy the information from the struct into the byte array
memcpy(bit_data, &data+1, *msglen-1);
bit_data[1] = typeID;
}
但这不起作用。我想我使用 memcpy 错误。我想将未知结构 T 复制到位置 bit_data[1] 到 bit_data[*end*]。实现这一目标的最佳方法是什么?
【问题讨论】:
-
不工作 没有任何意义。请准确说出发生了什么...
-
现在你修复了你的代码,它“工作”了吗?
-
如果您更新了问题中的代码以包含来自答案的修复,那么请不要这样做!它使答案变得无用,问题更是如此。
-
它现在可以工作了,这是一些简单的错误,但感谢您帮助我找到它们。我更新了这个问题,因为我认为它们不会是问题的原因,而只是轻率。
-
对于任何想要解决问题的人来说,现在这不是一个非常有用的问题。