memcpy和按分配复制之间的区别 [英] Difference between memcpy and copy by assignment

查看:163
本文介绍了memcpy和按分配复制之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Struct A
{
   uint16_t len;
   uint8_t  cnt;
   uint8_t  unit;
   uint32_t seq; 
};

此结构A被序列化为char * buf.如果我想反序列化各个值,例如:

This struct A is serialized into a char * buf. If I want to deserialize the individual values eg:

uint16_t len = 0;
memcpy(&len, buf, sizeof(len));

或者我可以做

uint16_t len = (uint16_t) buf;

哪个更好?或者两者都一样?

Which one is better or are both the same?

如果我愿意的话,还要反序列化整个结构

Also to deserialize the whole struct, if I just do

A tmp;

memcpy(&tmp, buf, sizeof(A));

这项工作正常吗?还是我应该担心编译器的填充等问题?

Would this work fine or should I be worried about padding etc from the compiler?

推荐答案

将数据复制到char[]缓冲区时,它可能无法在内存中正确对齐以作为多字节类型进行访问.将数据复制回struct可恢复正确对齐.

When the data is copied into char[] buffer, it may not be properly aligned in memory for access as multi-byte types. Copying the data back into struct restores proper alignment.

如果我想反序列化各个值,例如:

If I want to deserialize the individual values eg:

uint16_t len = 0;
memcpy(&len, buf, sizeof(len));

假设您已经将struct复制到了buf,这是完全有效的,因为该语言保证了初始成员将与结构的开头对齐.但是,将buf强制转换为uint16_t*是无效的,因为许多缓冲区在内存中没有正确对齐,无法寻址为uint16_t.

Assuming that you have copied the struct into buf, this is perfectly valid, because the language guarantees that the initial member would be aligned with the beginning of the structure. However, casting buf to uint16_t* is invalid, because the buffer many not be properly aligned in memory to be addressed as uint16_t.

请注意,获取除初始结构之外的其他结构元素需要计算适当的偏移量:

Note that getting elements of the struct other than the initial one require computing proper offset:

uint32_t seq;
memcpy(&seq, buf+offsetof(struct A, seq), sizeof(seq));

如果我愿意的话,还要反序列化整个结构

Also to deserialize the whole struct, if I just do

A tmp;
memcpy(&tmp, buf, sizeof(A));

这项工作正常吗?还是我应该担心编译器的填充等问题?

Would this work fine or should I be worried about padding etc from the compiler?

这可以正常工作.当您将struct中嵌入的所有填充内容复制到buf中时,它们都会连同实际数据一起返回到tmp中.

This would work fine. Any padding embedded in the struct when you copied it into the buf would come back into tmp, along with the actual data.

这篇关于memcpy和按分配复制之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆