Even though there has been a lot of talk about IronPython, there has been very little info about how to use it with C++/cli. I’ve actually found posts claiming that it is not possible to use IronPython with C++/cli.
Well, it is possible and easy, once you have a working example. If, not then … well, lets just hope your hair will grow back.
Ok, I’m never one to take the easy way out, but I started by creating a C# dll that called my IronPython script and then called the C# dll from C++/cli. That worked but seemed overly complicated. If you do not mind a middleman then I guess it is ok, but if you want to go straight from C++/cli to IronPython, read on.
When I first tried to write a call to an IronPython script from C++/cli, I tried a direct conversion of C# code into C++/cli code. That didn’t work, so I then tried using RedGate’s .Net Reflector and the C++/cli add-in for .Net Reflector. This got me 70% there. Combining both with some trial and error got me the rest of the way.
Funny, but when you look at the code, it seems so simple – yet getting there was not easy.
So, the following snippet shows a simple usage of IronPython as a scripting language. It takes the first parameter passed in prints it to the console, passes it to the IronPython script: ipyStrings.ipy, then prints to the console the value of the same parameter that was passed back. The IronPython code takes the string, prints it, reverses it, then sends it back.