5YrsLaterDBA
5YrsLaterDBA

Reputation: 34760

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

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?

Upvotes: 7

Views: 7192

Answers (2)

Jcl
Jcl

Reputation: 28272

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

Upvotes: 3

Earlz
Earlz

Reputation: 63835

See my blog post for a wrapper library that lets you determine what the JIT will define the managed type's size will be(at runtime). It works by using the sizeof IL instruction which isn't exposed at all in C#. It can be run with no special permissions at all and is verifiable.

Note: this may or may not be what you actually want. This might return 8 for a structure that actually only has a single byte in it. I don't really understand your question completely, so I'm not sure if this is actually what you want or not.

Upvotes: 0

Related Questions