IronPython: Consuming Extension Methods in IronPython Part II
This is an update from my original post: http://blogs.msdn.com/saveenr/archive/2008/11/14/consuming-extension-methods-in-ironpython.aspx
Before proceeding, please read the original article. It will help in understanding this one.
A QUICK RECAP FROM THE ORIGINAL POST
We have two assemblies. One assembly (the extender) contains extension methods that are assigned to a class in the other assembly (the extended).
And here is the corresponding source code
At this point both C# and F# can consume the extension methods defined in ClassLibB.
IronPython can’t.
IronPython requires us to add the “ExtensionType” attribute.
Our first attempt is this.
And the source code looks like this …
And now IronPython can consume the extension methods.
THE PROBLEM AND THE FIX
As you can see, I had to modify the source code of Assembly B. In a lot of real-world situations it’s not possible to modify Assembly A or B.
Here are some reasons why:
- You may not have the source code for assembly
- You have the source code, but modification is useless because the original assembly was signed by the author
- You have the source code, but you do not have the legal rights to modify or distribute the source
It this point, we’re stuck – but here’s the great news. Those ExtensionType attributes don’t have to be in either Assembly A or Assembly B. You can create a special Assembly C that has the sole purpose of storing these attributes. If you load Assembly C then IronPython can see the extension methods and it doesn’t require any changes to Assembly A or Assembly B.
IMPLEMENTING THE SOLUTION
And the source code looks like this:
VERIFYING THAT IT WORKS
Add a reference to AssemblyC and then import it. Then the extension methods will be visible to IronPython
PARTING THOUGHTS
- There’s still the pain of generating Assembly C – a future post will simplify this task
- Notice that Assembly C contains a tiny class “ClassLibC.ClassC”. In order for this all to work it seems that AssemblyC needs to contain at least one public class. (If you leave this palceholder class out, then you will be able to add a reference to Assembly C but the import will fail)
- Many thanks to Harry Pierson for letting me know that the ExtensionType attribute can be in any assembly.
- The source code is attached if you want to try this for yourself