How are objects stored in the memory in C#? [closed]
ClassC
that has int a, char b, long c, float d
and short e
- I know how each is stored each have their own set of bit but the amount of bits in each different - so how exactly does C# knows which bits should it access when I write OBJ.c
or OBJ.b
?
Is it somewhat possible to convert a whole (nonstatic) obj开发者_Go百科ect to an array of bytes\bit AND back?
OBVIOUSLY - If there's something like ClassC.TcpListener tcp
- it's a reference and stored as an int
(? Atleast it has the same size in bytes) - but still, how can it different between an int
and a pointer?Generally, this isn't something you need to care about unless you're P/Invoking a C library.
so how exactly does C# knows which bits should it access when I write OBJ.c or OBJ.b ?
It depends on the StructLayout of the object. There are two possible LayoutKinds.
The default is Sequential, where fields are stored in the same order they are declared, aligned appropriately. By default, a struct
containing your five fields would be stored as:
- offset 0-3:
int a
- offset 4-5:
char b
- offset 6-7: padding
- offset 8-15:
long c
- offset 16-19:
float d
- offset 20-21:
short e
A class
may have a slightly different layout due to vtable pointers, garbage collector metadata, etc. I'm not sure exactly how it works.
The other LayoutKind is Explicit, where you specify the field offsets explicitly.
Is it somewhat possible to convert a whole (nonstatic) object to an array of bytes\bit AND back?
Yes, the Marshal class will let you do this. See StructureToPtr and PtrToStructure.
it's a reference and stored as an
int
Pointers are not stored as int
s. That wouldn't work on 64-bit systems. IntPtr is used instead.
but still, how can it different between an int and a pointer?
At which level? C#? CIL? Machine language?
C# actually doesn't know where to access the members in the object. It's the JIT compiler that decides the layout of the objects.
It's possible to add attributes for the members so that the JIT compiler places the members in a specific way, which would make it possible to access all the members as a memory block, but it's rarely worth the effort.
Note: A pointer is 32 bits (int) on a 32 bit system and 64 bits (long) on a 64 bit system.
精彩评论