C#为什么sizeof的不安全以及如何在一个安全的方式得到一个结构的大小? [英] C# why sizeof is unsafe and how to get size of a struct in a safe way?

查看:221
本文介绍了C#为什么sizeof的不安全以及如何在一个安全的方式得到一个结构的大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我定义一个struct通过套接字来发送。我想获得它的大小,但的sizeof 是不安全的,同为 System.Runtime.InteropServices.MarshalSizeOf 。有没有办法得到它以安全方式的大小?

I've defined a struct to send via socket. I'd like to get the size of it but sizeof is unsafe and the same for "System.Runtime.InteropServices.MarshalSizeOf". Is there a way to get its size in a safe way?

推荐答案

有没有办法做到这一点的管理结构。 Marshal.SizeOf 只会返回上包括结构的的封...类型的数据的大小可能的是托管类型正确在某些平台上,而不是别人。

There is no way to do it for managed structs. Marshal.SizeOf will only return the size of the data on the marshaled types that comprise the struct... that MIGHT be correct for the managed types on some platforms, but not on others.

这是由设计使JIT可以根据其上运行的平台上不同打好结构。

This is by design so the JIT can lay structs differently depending on the platform it runs on.

在此处了解详情:克里斯Brumme的博客

这篇关于C#为什么sizeof的不安全以及如何在一个安全的方式得到一个结构的大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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