Search code examples
c#ironpython

IronPython returns wrong type when using class in classy library


Can someone recommend a workaround for this ironpython bug?

I have a class contained within an external class library. I consume this class inside an embedded ironpython instance. When the class is retrieved from the scope by my c# app, the classes don't seem to match up!

My python script:

import sys
import clr
from ExternalAssembly import *
from IronPythonBug import *

internalClass = InternalClass("internal")
externalClass = ExternalClass("external")

My c# app:

internalClass = scope.GetVariable("internalClass");
externalClass = scope.GetVariable("externalClass");

if (internalClass is InternalClass)
    Console.WriteLine("IternalClass matches");
else
    Console.WriteLine("Error: InternalClass does not match");

if (externalClass is ExternalClass)
    Console.WriteLine("ExternalClass matches");
else
    Console.WriteLine("Error: ExternalClass does not match");

Console output:

IternalClass matches
Error: ExternalClass does not match

Solution

  • This is caused by CLR loader contexts. The call to Assembly.LoadFile loads another copy of the assembly into a different context - giving you a duplicate set of types but with different identities. Instead of using Assembly.LoadFile to get the assembly object use typeof(ExternalClass).Assembly.