I have already implemented a .Net version of Lovecalc, but I figured it would be a nice test to see whether I could get .Net code to run the native C version of Lovecalc. So just like I did for Perl, I used Mono and C# to create .Net bindings for Lovecalc. Actually, the code is a drop-in replacement for the .Net lovecalc library, and it works with LovecalcGUI and loves.
Creating .Net bindings for a C library with Mono on Linux is actually quite a snap once you know where to look. The Mono documentation has a document on this, and LinuxGazette has an excellent tutorial. Once you know what you need is called “Platform Invoke”, or “P/Invoke” for short, there are dozens of great articles about it. Basically adding a line like:
[DllImport("liblovecalc")]
static extern int lovecalc(String name1, String name2);
is enough to start running native code from .Net! Really neat. The one thing I encountered though was that you cannot access variables from a C library directly: you’ll need getters and setters. The property concept of C# makes it possible to still use the C variables as C# variables though:
/** Maximum length of calculation string */
public static int maxLength {
get { return get_max_strlen(); }
set { set_max_strlen(value); }
}
Really neat! Just run the code while the liblovecalc.so is somewhere in your library path and it all just works! I’m beginning to like C# more and more! Does that make me evil?
Download the .Net bindings for Lovecalc from the project page. And fetch lovecalc 2.2 while you’re at it (this actually contains the bindings as well), because the bindings require this version at least.