Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mono.Cecil Module of BaseType is incorrect

Tags:

c#

mono.cecil

I am loading two assemblies using AssembliyDefinition.ReadAssembly

In AssemblyA I define ClassA.

In AssemblyB I define ClassB : ClassA.

When I inspect the TypeDefinition.BaseType of ClassB I get that its Module is AssemblyB.

I wouldbe expected that the its module would be AssemblyA, since the base type of ClassB is ClassA and it is defined in AssemblyA.

This shows up as an error for me because when i try to do classB.BaseType.Resolve() i get an error, which probably happens since it searches for ClassA in the wrong assembly.

Any ideas anyone?

Thanks

like image 737
ravyoli Avatar asked Jul 26 '11 15:07

ravyoli


1 Answers

Your expectation is incorrect.

Cecil, unlike System.Reflection, and for a module, makes the distinction between a type defined in this module: a TypeDefinition, and a type defined in another module: a TypeReference.

That's the reason why BaseType is a TypeReference instance, and in your case, the reference to ClassA is inside AssemblyB. If you want to see where the BaseType is defined, and not where it's used, you have to use the Scope property of TypeReference.

If you have an error in Resolve, that's a completely different issue. But then you don't show anything about what this error is, so we'll have to guess that the assembly resolver doesn't know where to look for AssemblyA. And according to your comment, that's the case. Here's what you can do:

var resolver = new DefaultAssemblyResolver ();
resolver.AddSearchDirectory ("path/to/AssemblyA");
resolver.AddSearchDirectory ("path/to/AssemblyB");

var a = AssemblyDefinition.ReadAssembly (
    "path/to/AssemblyA/AssemblyA.dll",
    new ReaderParameters { AssemblyResolver = resolver });

var b = AssemblyDefinition.ReadAssembly (
    "path/to/AssemblyB/AssemblyB.dll",
    new ReaderParameters { AssemblyResolver = resolver });

This way you make sure that all your assembly share a common resolver, which knows where to find your assemblies. And Resolve will work just fine.

like image 148
Jb Evain Avatar answered Oct 17 '22 18:10

Jb Evain