As commented by Victor Stafusa, two common alternatives for consuming native code are the JNI (standard Java engine) and JNA (a popular library to consume C libraries).
In a rough simplification we can say that the main difference between the two is that with JNI most of the "mapping" is done on the C/C++ application side. With JNA mapping is done on the Java side.
JNA is an abstraction about the convenient JNI to work with C; mapping C++ code ends up giving a lot of work and is not always possible.
JNI
When using JNI you have a development process that usually consists of:
- Create a class with native marked methods (
native
) in Java.
- Compile the class (e. g.,
javac
)
- Create headers and stubs C/C++ for the class in question (using
javah
)
- Write the implementation of "bridge" in C/C++. for example, delegating calls to your dll original
- Create a shared library with the code you wrote (e. g.,
libPonte.dll
)
- Load the native library (e.g., using
System.loadLibrary
)
Here are some links about JNI:
- IBM developerWorks - Java Programming with JNI
- Oracle Blogs | Moonocean - A simple example of JNI
- Oracle - Java Native Interface Specification
JNA
Already the integration using JNA usually starts from the headers library documents, following the following process:
Identify native functions you want to call.
Include the archive jna.jar
in the classpath of the application
Declare a mapping interface on the Java side (inheriting from Library
) or a class with methods native
and direct mapping. The methods of this interface / class must be a counterpart of the C functions you want to call.
Map structures, function pointers and other particularities. Structs in C are mapped to Java classes that inherit from Structure
. C function pointers are mapped to Java classes that inherit from Callback
.
- Optionally steps 3 and 4 can be automated. Tools such as Jnaerator are capable of generating the mapping of the dll and of headers library.
Load native library with methods loadLibrary
or register
Here are some links about JNA:
- Calling C code from Java using JNA
- Getting Started with JNA
- JNA API Documentation
It is necessary to mention that there are other libraries with the same purpose of JNA; the choice of library usually involves a trade-off between simplicity and control. Honorable mention for the SWIG capable of generating interfaces for multiple languages (including Java / through JNI) and Bridj which sells as an alternative to the JNA with "real" support to the C++.
Diving a little deeper you find the legacy world of distributed objects, including libraries like JACOB (for WITH) and Jacorb (for CORBA) but this is a subject for another question (specific about CPI).
The way is the JNI yes, but unfortunately I know little of it. There is also the JNA. Keep my +1 because I also have an interest in this.
– Victor Stafusa
Here’s an example using JNI and JNA. http://blog.caelum.com.br/scrindo-metodos-nativos-em-java-com-jni-e-jna/
– Reginaldo Rigo