Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# what is the size of unmanaged object?

Tags:

c#

Read definition of Marshal.SizeOf(). It says this: The size returned is the size of the unmanaged object. The unmanaged and managed sizes of an object can differ. Is that means Marshal.SizeOf will return you the definition size but not the actual memeory allocated size because there are may have some padding for alignment?

For example:

struct MyStruct
{
   char c;
}

The size will be 1 byte for unmanaged object (unmanaged size) if I use Marshal.SizeOf() but may be 2 or 4 bytes for managed object (managed size) if I use sizeof(). Am I right?

like image 761
5YrsLaterDBA Avatar asked Mar 10 '10 17:03

5YrsLaterDBA


1 Answers

The only meaning of Marshal.SizeOf is size of unmanaged memory block required for Marshal.StructureToPtr method. SizeOf may not be equal to managed structure size, and to unmanaged structure size. StructureToPtr may serialize a structure with or without padding, it is internal details. SizeOf only reports how much memory this operation requires, and anything else.

like image 196
Alex F Avatar answered Sep 28 '22 13:09

Alex F