recipe № 023

Calling code from shared library (adapter pattern)

If you want to call method from shared library, there is nothing special here, when it comes to JNI. Calling shared methods from shared libraries is a typical sample of Adapter Pattern applied to Java calling native code. In this case, typically, you already have some sort of native code (written in C/C++/Fortran) and you want to make it available inside your Java code. In this case, JNI serves as adapter and allows to re-use already existing code base. Most common use case is very similar to picture below

In fact, there is not much to do from our side. All we need to do, is to make sure that we have shared library we want to link with and we have to make sure that library will be linked with shared library that contains JNI code. That’s all. Of course, there might be some issues here (I will show how to overcome them in some other place), but in general, that’s it.

Let’s say we have this special function we want call.

and we have created shared library that contains it

all we have to do, is to make sure that code we want to use from Java (e.g. this one)

is linked with the library that contains function we want to call.

That’s all. You can find full sample here: recipe № 023.