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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With