Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a TypeDefinition from another Assembly

Tags:

c#

mono.cecil

This one is driving me crazy.

AssemblyDefinition asm1 = AssemblyDefinition.ReadAssembly(example);
AssemblyDefinition asm2 = AssemblyDefinition.ReadAssembly(example2);
asm2.MainModule.Types.Add(asm1.MainModule.Types[0]);

Whenever I try to execute the above code I get this error 'Type already attached' I decided to look this error at MonoCecil source and I found it throws this error because the Type's MainMoudle isn't asm2 MainModules. So I decided to Copy that Type to a new one.

TypeDefinition type2 = new TypeDefinition("", "type2",  Mono.Cecil.TypeAttributes.Class);
foreach (MethodDefinition md in asm2.Methods )
{
        type2.Methods.Add(md);
}

And then add this type to my assembly normally but this throws another error, 'Specified method is not supported.'. Any thoughts why I am getting this error?

Edit: Just to add, the type I'm trying to add contains some methods which uses pointers. Might this be the problem? As far as I know mono supports that but not mixed mode.

like image 975
method Avatar asked Jan 20 '12 14:01

method


1 Answers

I'm afraid there's no built in, easy way to do this.

When you read an assembly with Cecil, every piece of metadata is glued together by the Module the metadata is defined in. You can't simply take a method from a module, and add it into another one.

To achieve this, you need to clone the MethodDefinition into a MethodDefinition tied to the other module. Again, there's nothing built-in yet for this.

I suggest you have a look at IL-Repack, which is an open-source ILMerge clone. It does exactly that, it takes types from different modules, and clone them into another one.

like image 127
Jb Evain Avatar answered Oct 05 '22 20:10

Jb Evain