在结构或联合上使用 ntohl
ntohl
采用 uint32_t
。我有许多不同成员的消息(类型为 uint32_t
或 uint16_t
)。是否可以正确传递整个接收到的struct
或union
并将其转换为uint32_t
,然后reinterpret_cast
进入我的union
或struct
?
我的做法是逐行列出union
或struct
的每个单独成员,并将其传递给ntohl/s,如下msg .member = ntohl(msg.member);
但这很麻烦!
数据结构从 C# .NET 应用程序 (Windows) 整体传输到 Linux 应用程序。
当我尝试时,
void* ptr = &msg;
uint32_t temp = (uint32_t)ptr;
编译器抱怨:
错误:从“void*”转换为“uint32_t”会丢失精度
ntohl
takes a uint32_t
. I have messages with many different members (of type uint32_t
or uint16_t
). Is it possible to properly pass in the entire received struct
or union
and have it converted to say uint32_t
and then reinterpret_cast
into my union
or struct
?
How I have been doing it is listing, line-by-line, each individual member of the union
or struct
and passing it to ntohl/s like this msg.member = ntohl(msg.member);
but that is cumbersome!
The data structures are transferred in whole from a C# .NET application (Windows) to a Linux application.
When I tried,
void* ptr = &msg;
uint32_t temp = (uint32_t)ptr;
The compiler complains that:
error: cast from 'void*' to 'uint32_t' loses precision
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不,你不能。仅在您的结构仅包含一个
uint32_t
变量的情况下。此外,您必须根据不同的变量大小使用不同的
ntoh
函数。No, you can't. Only in the case that your struct only contains one
uint32_t
variable.Besides, you must use different
ntoh<X>
functions depending the different variables sizes.您可以使用 Google 的协议缓冲区。
You can use Google's Protocol Buffers.