Monday, December 01, 2008

Adding References to Assemblies in IronPython

The 'first point' of interoperation between Python code and the .NET framework is the clr module. This allows you to dynamically add references to .NET assemblies in order to be able to import classes from the namespaces they contain.

The clr module has a bewildering array of different functions for adding references to assemblies, and each of them have slightly different semantics and use cases. Dino Veihland (IronPython Developer) recently posted a very useful explanation to the mailing list:

clr.AddReference(str) will first try Assembly.Load and then try Assembly.LoadWithPartialName - this should mean that trying with the strong name won't do anything because LoadWithPartialName will do that for you. This is kind of the one-stop shopping for loading assemblies in the GAC or the app base. If those don't work it will also ultimately search sys.path when the load fails.

clr.AddReference(asm) will just add the assembly that you've already loaded - this is useful if you can load the assembly using some other mechanism (e.g. Assembly.LoadFrom or loading from byte array or whatever)

clr.AddReferenceToFile(str) will search sys.path for the file and load it from there using Assembly.LoadFile. This is good to not have the normal Assembly.Load/LoadWithPartialName mechanisms get in the way.

clr.AddReferenceToFileAndPath(str) will take a fully qualified path, append it to sys.path, and then do Assembly.LoadFile with the path. This is just convenience for quickly adding a fully qualified assembly.

There's also Load* variations which return the assembly object which you can dot through without altering what you can import.

Usually when debugging assembly load failures I use fuslogvw.

No comments:

Post a Comment

Note: only a member of this blog may post a comment.