Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

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?

like image 711
5YrsLaterDBA Avatar asked Mar 10 '10 16:03

5YrsLaterDBA


1 Answers

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

like image 50
Jcl Avatar answered Sep 29 '22 17:09

Jcl