C # what is the size of an unmanaged object?

Reading the definition of Marshal.SizeOf(). It says the following: The size returned is the size of the unmanaged object. The unmanaged and managed sizes of an object can differ. The size returned is the size of the unmanaged object. The unmanaged and managed sizes of an object can differ. This means that Marshal.SizeOf will return the definition size to you, but not the actual size allocated to the memeory, because there may be some extras for alignment?

For example:

 struct MyStruct { char c; } 

The size will be 1 byte for an unmanaged object (unmanaged size) if I use Marshal.SizeOf() , but there may be 2 or 4 bytes for a managed object (managed size) if I use sizeof( ). I'm right?

+6
c #
source share
2 answers

The only value of Marshal.SizeOf is the size of the unmanaged memory block required by the Marshal.StructureToPtr method. SizeOf may not match the size of the managed structure and the unmanaged size of the structure. StructureToPtr can serialize a structure with or without filling, these are internal details. SizeOf only tells you how much memory is required for this operation and something else.

+2
source share

Just write a small sample application.
MyStruct in your example is 1 in both the managed and unmanaged cases.
The actual size for more complex objects may also depend on things such as alignment and other OS-dependent things.

+1
source share

All Articles