Re: Че такое .custom в MSIL?
От: NoOneKnows  
Дата: 27.11.06 00:07
Оценка: 70 (5) :))
Привет, Коллега!

Знаешь, было бы здорово, если бы проверил/показал версии ildasm'a и ilasm'a. Сдается мне, ты дизасемблишь под старшей версией CLR, а собрать пытаешься под младшей. Впрочем, я далеко не специалист, так что могу ошибаться.

— Рамиль, так че ты вообще лезешь со своими пятью копейками, если "не специалист"?
— Отстань от меня, псих с раздвоением личности! Под руки попалась замечательная книжка "Inside Microsoft .NET IL Assembler", тринадцатая глава которой так и называется "Custom Attributes". Может быть, Серж Лидин специально поместил ее под счастливым номером, недвузначно намекая на загадочную природу .custom атрибутов? Однако, прочь демагогию, — ближе к делу!

Итак, что же такое Custom Attribute? — Это элемент метаданных, задумывавшийся как универсальный инструмент расширения оных. Атрибуты эти, конечно, не меняют структуру метаданных (а кто бы осмелился посягнуть на святыню CLR?) Тем не менее они играют роль близкую к generic'ам, позволяя создавать новые типы по образу некоторых "шаблонов". Точнее говоря, custom attribut'ы дают возможность указать дополнительную информацию об элементах метаданных, не предоставляемую самими метаданными.

В основном информация эта предназначена для компиляторов, линкеров и дебагеров.

Серж приводит пример, когда custom attribute очень и очень кстати:

Think of the following simple example. If we want managed code to interoperate with classic COM applications, we need to play by the classic COM rules. One of these rules is that every exported interface must have a globally unique identifier, a GUID, assigned to it. The runtime generates GUIDs on the fly, but we might need not just any GUID but rather a specific GUID assigned to a class. What do we do? Add another field to the TypeDef record to store an offset in the #GUID stream? This would surely help to reduce the size of the metadata tables, especially when we consider that only a small fraction of all TypeDefs might ever be used in COM interoperation. To solve the problem, we can introduce a GUID-carrying custom attribute—actually, we have one already: System.Runtime.InteropServices.GuidAttribute—and assign this attribute to any TypeDef participating in the COM interoperation.


Продолжая пересказ книги, находим и способ объявления этих мифических Касто-Матрибутов:

The ILAsm syntax for declaring a custom attribute is as follows:

.custom <attribute_type> [ = ( <hexbytes> ) ]
or, considering the limitation imposed on <attribute_type> in the first release of the common language runtime:

.custom instance void <class_ref>::.ctor(<arg_list>)
[ = ( <hexbytes> ) ]
where <class_ref> is a fully qualified class reference, <arg_list> is an argument list of the instance constructor, and <hexbytes> is the sequence of two-digit hexadecimal numbers representing the bytes in the custom attribute’s blob.


Слова "considering the limitation imposed on <attribute_type> in the first release of the common language runtime" и навеяли мысли о версиях.

— Так че там за ограничения ?!
— Я — не специалист . А вот Серега, похоже, знает, что пишет:

The Type entry of a custom attribute is a coded token of type CustomAttributeType and hence theoretically can be one of the following: TypeRef, TypeDef, Method, MemberRef, or String. In fact, in the first release of the common language runtime, the choice is limited to Method or MemberRef because of the requirement that the type of a custom attribute must be an instance constructor and nothing else. The class whose instance constructor represents the custom attribute type should be derived from the abstract class [mscorlib]System.Attribute.


— Эх, Неспециалист, дал бы хоть ссылку на книгу, человек бы сам разобрался и понял бы все...
— _Sphinx_, на тебе ссылку. Хотел найти еще Е-бук Expert .NET 2.0 IL Assembler, но неуспешно. Пираты медленно работают .



PS: Я не псих . Спасибо за внимание. Надеюсь, что-то да будет полезным...
С уважением, Рамиль Сам Ду Нар.
Почти самый отрицательный
Автор: NoOneKnows
Дата: 08.06.06
РСДНовец.
 
Подождите ...
Wait...
Пока на собственное сообщение не было ответов, его можно удалить.