Adding TypeDefinition from another assembly

It drives 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 "The type is already attached" I decided to look at this error in the MonoCecil source, and I found that it throws this error, because Type MainMoudle is not asm2 MainModules. So I decided to copy this 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, but it causes another error: "The specified method is not supported." Any thoughts why I get this error?

Edit: just to add, the type I'm trying to add contains some methods that use pointers. Perhaps this is a problem? As far as I know, mono supports this, but not mixed mode.

+4
source share
1 answer

I am afraid there is no built-in and easy way to do this.

When you read the assembly with Cecil, each piece of metadata is glued together by the module in which the metadata is defined. You cannot just take a method from a module and add it to another.

To achieve this, you need to clone the MethodDefinition method in MethodDefinition bound to another module. Again, there is nothing built-in for this.

I suggest you take a look at IL-Repack , which is an open source ILMerge clone. He does just that, he accepts types from different modules and clones them into another.

+6
source

Source: https://habr.com/ru/post/1392059/


All Articles