Chris Marisic
Chris Marisic

Reputation: 33098

What is the purpose of the byte array in AssemblyBuilder.SetCustomAttribute

Are there any meaningful ways to use

public void SetCustomAttribute(
    ConstructorInfo con,
    byte[] binaryAttribute
)

from AssemblyBuilder.SetCustomAttribute

Clarification: by meaningful, I mean what kind of data would you ever want to fill that array with? What does it do with it?

Is there something like I could binary formatter serialize an existing Attribute and pass it that data?

Upvotes: 3

Views: 412

Answers (3)

vcsjones
vcsjones

Reputation: 141638

Because attribute storage is a magic science. They are always stored using a binary format that is encoded, and in this case it's just giving you raw write-access to the binary content of the attribute. Largely, this would be used by someone implementing their own compiler, or are trying to squeak out every bit of performance as possible. You can't just put anything you'd like in there, you are expected to follow the CLI's specifications.

For example, the value of the constructor arguments in an attribute must be encoded. Take for example the following attribute:

internal class MyAttribute : Attribute
{
    public string Foo;
}

And if we apply it with something like [MyAttribute(Foo = "4")] to a token, it must serialize:

  • The member being initialized
  • The type of member being initialized (field or property)
  • Whether or not the attribute is inherited
  • The value
  • Etc.

So it gets compiled into something like this:

.custom instance void Dummy.MyAttribute::.ctor() = ( 01 00 01 00 53 0E 03 46 6F 6F 01 34 )

These values mean:

  1. The prolog (the encoding version). This starts with the byte value of 0x0001 (the version has never changed, AFAIK)
  2. The number of Constructor arguments (1 in this case) (So far this takes care of the first 4 bytes, 01 00 01 00.
  3. The type of constructor argument. 0x53 if a field (See CorSerializationType for all of them). Type is 0x50, Property is 0x54, and there are a few others. (This explains the 5th byte, 0x53).
  4. Other details about the encoding of the data (a string).
  5. The field name (Foo = 0x46 0x6F 0x6F)
  6. The length of the string (0x1)
  7. The UTF8 value of the string 0x34 = "4"

Upvotes: 5

Stephen Gennard
Stephen Gennard

Reputation: 1910

The encoding is documented in "MS Partition II" section 23.3, which can be downloaded @

http://download.microsoft.com/download/7/3/3/733AD403-90B2-4064-A81E-01035A7FE13C/MS%20Partition%20II.pdf

re: http://msdn.microsoft.com/en-us/netframework/Aa569283.aspx

Upvotes: 2

stefan
stefan

Reputation: 2886

It will allow precompiling attributes and just geschmack them into the binary instead of going thro the builder.

Upvotes: 1

Related Questions