Calling existing C++ libraries from Java using JNI

May 15, 2013

You don’t “convert C++ file to java style”. You need to create a JNI wrapper around your existing C++ code. This JNI wrapper is actually C++ code that can be called by Java.

By wrapper I mean that you shouldn’t have to modify your existing C++ code base. This wrapper, or better said this binding should generally be very thin. The wrapper code is only meant to expose existing functionalities, not to implement them. It is better to leave the implementation in the (portable) C++ code base.

If the code base isn’t too large, then I recommend that you write this wrapper by hand, as explained inThe JavaTM Native Interface Programmer’s Guide and Specification

Now, if you are trying to bind a large library, it may be problematic. So, in regard to tools, I haven’t used that, but have a look at SWIG, and the relevant SWIG Java documentation.

According to the homepage description, it’s what you’re asking for:

SWIG is typically used to parse C/C++ interfaces and generate the ‘glue code’ required for [Java, Python, PHP, …] to call into the C/C++ code.

javah can be useful in certain cases, but it’s not what you ask for. It extracts JNI boiler plate code out of native declarations found in Java classes.