Tuesday, February 17, 2009

Consuming Extension Methods in IronPython Parts II & III

A while ago Saveen Reddy posted an entry on using extension methods from IronPython.

Extension methods allow you to extend types and interfaces in C# by defining new methods in a *different* assembly. IronPython can only see these extension methods if they are decorated with the ExtensionType attribute.

This is fine if you have access to the source of the extension methods to and can recompile with this attribute. In part II Saveen shows how you can make the extension methods visible to IronPython without having to modify the assemblies containing the extensions - by creating a third assembly:
Part III does some weirder magic using the CodeDom. It allows you to activate the extension methods from inside IronPython without having to create the extra assembly used in Part II.
  • The Isotope.IronPythonUtil is an assembly that contains a method CreateIronPythonExtensionMethodAssembly()
  • CreateIronPythonExtensionMethodAssembly() loads an assembly from a DLL
  • This loads all the assemblies to which that first assembly refers
  • It finds all the extension methods in the first assembly
  • builds a CodeDOM of all the ExtensionType attributes
  • builds a placeholder class (see previous post about the need for this)
  • and generates a DLL
  • The original code generated a “C#” file and used CodeDOM to compile it to an DLL. This one generates a CodeDOM manually so it is faster to create the Dll.
  • The source code is included as an attachment

No comments:

Post a Comment

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