[Mono-dev] Re: Adding Custom Attributes to Assembly

Jb Evain mono at evain.net
Thu Feb 23 13:39:33 EST 2006


Sadly, using Cecil requires a bit of knowledge about the metadata  
format and how the metadata is serialized.

To add a custom attribute, you have to import (ModuleDefinition.Import 
()) the type of the custom attribute into the assembly in which the  
custom attribute will be used.

Then you have to import the appropriate constructor of the custom  
attribute type, to get a MethodReference you will used to instantiate  
a CustomAttribute object. Once you have this custom attribute, you  
can add it to an ICustomAttributeProvider, wich holds a collection of  
custom attribute.

Finally, you can write back the assembly to the disk.


On Feb 21, 2006, at 3:04 PM, vijaya raghava mutharaju wrote:

>   Hi,
>             I was thinking if the following code would do what I  
> was asking of
>                  1)  AssemblyDefinition assembly1 =  
> AssemblyFactory.GetAssembly("MyAssembly.exe");
>                       AssemblyDefinition assembly2 =
> AssemblyFactory.GetAssembly("AnotherAssembly.exe");
>                       foreach(.........)
>                        {     if(type is  MyAttribute)
>                              {  // Import MyAttribute into assembly2
>                          }}
>                 2)  MyAttribute attribute = new MyAttribute("some  
> arguments");
>                      But it still leaves the issue of how to assign  
> a proper parent(in my case a class in assembly2) to MyAttribute.
>               Excuse me if the above code is completely off target.  
> Iam new to Cecil.
>           Thank you.
> On 2/21/06, vijaya raghava mutharaju <m.vijayaraghava at gmail.com>  
> wrote:
>        Hello,
>             I want to add custom attributes to an existing  
> assembly. I want to do the following steps.
>                      1)  Refer the class MyAttribute which is in  
> the assembly MyAssembly.exe, so that I can import into the current  
> assembly - AnotherAssembly.exe
>                       2)  Add this attribute (MyAttribute  
> constructor with proper arguments) on top of some of the classes in  
> AnotherAssembly.exe which is the one that is to be modified.
>                       3) Save it back to disk - I know  
> AssemblyDefinition.SaveAssembly() can be used for that.
>            Please can you tell me how these steps can be done using  
> Mono.Cecil.
>            Thank you.
> _______________________________________________
> Mono-devel-list mailing list
> Mono-devel-list at lists.ximian.com
> http://lists.ximian.com/mailman/listinfo/mono-devel-list

More information about the Mono-devel-list mailing list