CLR class memory layout

2019-03-18 23:02发布

问题:

What is the memory layout of a CLR class?

Coming from a C++ background, the memory layout of a C++ class with virtual functions starts with a v-table pointer, and then the data members of the class follow in memory.

Do CLR classes with virtual functions have a v-table pointer? Is this pointer the first field in the class memory layout? Are there any extra fields in a CLR class memory layout in addition to programmers' defined data members? And what do these extra fields represent?

回答1:

It's implementation specific, but this article gives a description of what was present in the Microsoft .NET implementation, for CLR v2. I suspect it's the same for CLR v4, but I couldn't guarantee it. Look for a section called "ObjectInstance" for the details - but you may find the whole article interesting.

According to the article, there are basically two bits of header: the sync block which is used for locking, and the type reference which is basically a pointer to type information (including the vtable).



回答2:

The original "Jit and Run" article is still around, as a chm file. Just follow the MSDN instructions to be able to read:

On most versions of windows you must first save these files to your local machine, and then unblock the file in order to read it. To unblock a file, right click on it, and select properties, and then select the ‘unblock’ button. The content will then be available to read

However, the venerable Jon Skeet guessed wrong - and object memory layout has indeed changed. Sasha Goldstein gives an up-to-date (CLR v4) survey of the layout, here.



标签: .net clr