Interop between Java and .NET

Recently, I was presented with an interesting challenge. There was a need to call a .Net API from within Java. There are several options to accomplish this. The most native option is to add a C++ wrapper around the .Net API and use Java Native API to invoke the C++ function.

Another interesting option is to use the open source library of jni4net. It is an interesting option because it allows for Java to interact with .Net classes via proxy generation and loads the CLR into the same process as the JVM.

I created my .NET API in C# 4.0 and used the proxygen.exe to generate the Java equivalent proxies of the C# API. The proxygen uses introspection to create the equivalent Java classes and compiles the new classes in C# and Java to create the intermediate layer.

Once this is done, you can reference the proxy classes within the Java program and the calls to their methods and then handed off to the equivalent C# classes.

There are some gotchas that one discovers with this approach. Not all classes on both sides have equivalency. For example, if a method returns a string from C#, its easily translated into a string in Java. But same is not true for Exception class. You cannot trap a call in Java in a try catch block and catch a .Net exception.

But for most implementations this library worked great.

This entry was written by Amit, posted on August 11, 2011 at 3:50 pm, filed under Uncategorized. Bookmark the permalink. Follow any comments here with the RSS feed for this post.

Timeline

Comments are closed.