C# why sizeof is unsafe and how to get size of a struct in a safe way?

后端 未结 2 472
悲哀的现实
悲哀的现实 2021-01-05 14:28

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.MarshalS

2条回答
  •  滥情空心
    2021-01-05 15:20

    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.

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

    More info here: Chris Brumme's blog

提交回复
热议问题