5

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.

svick
  • 236,525
  • 50
  • 385
  • 514
method
  • 1,369
  • 3
  • 16
  • 29

1 Answers1

6

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.

Jb Evain
  • 17,319
  • 2
  • 67
  • 67
  • Hmm, I will take a look at it, but I have a last question, if I looped through each instruction of the method and then add it to a new method then adding it to my type. Will that work? – method Jan 20 '12 at 15:46
  • 2
    @user959615 it won't, because the instructions can have metadata as operands, like a method for a call instruction. It needs to be changed to a reference to the method into the new module. – Jb Evain Jan 20 '12 at 16:18