Tutorial :Calling C# code from Java?


Does anyone have a good solution for integrating some C# code into a java application?

The code is small, so I could re-write in java, but I would rather reuse the code if possible. Don't repeat yourself, etc.

Also, I know I can expose the C# as a web service or whatever, but it has some security/encryption stuff in there, so I would rather keep it tightly integrated if possible.

Edit: It's going to be on a server-based app, so "downloading" another runtime is irrelevant.


There is an IL to Java Bytecode compiler GrassHopper which may be of use to you. I've never tried it though.

I'd look at rewriting your code in Java though

EDIT: Note that Grasshopper seems to be no longer available.


You would use the Java Native Interface to call your C# code compiled into a DLL.

If its a small amount of C#, it would be much easier to port it to Java. If its a lot, this might be a good way to do it.

Here is a highlevel overview of it:


Your other option would be to create a COM assembly from the C# code and use J-Interop to invoke it.



I am author of jni4net, open source intraprocess bridge between JVM and CLR. It's build on top of JNI and PInvoke. No C/C++ code needed. I hope it will help you.


If it's short, I think you're better off re-writing the code in java. Downloading one 50Mb runtime is bad enough.


We used JNBridge for this, and it worked great. It handles Java->.NET and vice versa, all in-proc.


If you do not want to rewrite hadle it as an Inter-process communication and choose one of following:

  • Named pipes
  • Sockets
  • SOAP


I would rewrite it if it's not too much trouble. The web service would work, but it seems like that would be a lot of overhead just to reuse a little code.


http://www.infoq.com/articles/in-process-java-net-integration suggests running CLR and JVM in the same process space and passing calls back and forth. It sounds very efficient. I'm going to give it a try and integrate it into Jace if it works well.


If it is a piece of code that is exposable as a command line utility, I just make the other host language use a system call to execute the utility.

If your C# app needs to call Java, compile a special Java main that takes appropriate command line args and returns text output.

It the oldest, simplest method.

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »