Java

Mono is able to run Java code side-by-side with .NET as well as having Java and .NET object interoperate with each other. This is done with IKVM the Java VM implementation that runs on top of .NET and Mono. IKVM was developed by Jeroen Frijters for the .NET Framework. Zoltan Varga ported it to Mono and fixed the Mono runtime to support the features required by IKVM. The class library runtime for IKVM is the GNU Classpath, which is rapidly advancing but not entirely complete. IKVM is fully supported by Mono and its part of the standard Mono package distribution. As it stands today, it is able to run popular applications like Eclipse and Derby.

There are two possible ways of using IKVM: one is to use it as a Just-in-Time compiler which translates the Java bytecodes into .NET Intermediate Language as it goes. But this means that at runtime you are compiling things twice: the Java-to-CIL JIT and the CIL-to-Native JIT.

We are going to build some samples using Gtk#

Gtk# is really a bad name. Because Gtk# is not limited to C#, any programming language in the .NET framework can use it today and because it covers more than only the Gtk API, it covers various other components of the GNOME Development Platform.

Exposing .NET Libraries to Java

Now, Gtk# is a .NET assembly (this is the ECMA lingo for “library”), and Java does not know anything about this. It is necessary first to generate some stubs for these classes to let the Java compiler knows about the types defined in the C# world. This is done using the netexp.exe program from IKVM, like this:

This produces a Demo.class file that contains the Java bytecodes. The -classpath file instructs the Java compiler to find the type definitions on the gtk-sharp.jar file that we had previously produced with ikvmstub.

Running Our Java Code in Mono

Now, it is not possible to run this directly in Java, since the jar files produced by netexp.exe are only stubs, so we will need to run this in the Mono world using IKVM in JIT mode:

ikvm -classpath .:gtk-sharp.jar Demo

The above just sits there waiting for events, so feel free to kill that. We will now add some meat to the program, this is a slightly more interesting sample:

The above is basically translating Demo.class from JVM bytecodes to ECMA CIL, then the Mono JIT translates that into native x86 code. The next step is to precompile the Java code directly into .NET code, which will skip the double JIT process:

The above compiled the code directly into a a Mono/.NET executable. To run it, just do:

mono Demo.exe

Compiling Java Code to x86 Code

But we can go one step further. We can avoid completely the JIT process by precompiling the .exe file which contains instructions in the ECMA Common Intermediate Language into native x86 code using Mono’s Ahead-of-Time compiler, to do this, type: