Loading the DLL is only the easiest step.
As it is not really trivial to call a method of a DLL from Java this answer is only a summary of hints what you have to do to call a function from a DLL. The whole story would fill a book. And in fact there are several books about JNI (Java Native Interface).
To call a function in a native library you have to declare a method in your java class as native with the java keyword native
. The declaration of this method must not have a body.
The name of the function exported from your DLL must match the following pattern:
Java_classname_methodname
where classname
is the name of the class where you declared the native method methodname
.
For example if you declare a native method private native void sayHello()
in your class MyClass the name of the DLL's function would be: Java_MyClass_sayHello
Also keep in mind that the function must be exported from the DLL with the correct calling conventions JNIEXPORT and JNICALL which are defined in the header file jni.h that comes with your JDK (see include folder)
Every function of a DLL to be called from Java also must have two "hidden" arguments as first parameters (JNIEnv *env, jobject obj)
.
env
is a pointer to the calling JVM which allows you callback into the JVM and obj
is the object from which the method was called.
So the whole definition of the DLL's method in our example would be:
JNIEXPORT void JNICALL Java_MyClass_sayHello(JNIEnv *, jobject);
Due to these restrictions of JNI a DLL called from your code must be specifially made for your code. To use an arbitrary DLL from Java you usually have to create an adapting DLL with the conventions of JNI that itself loads the "target" DLL and calls the required functions.
To generate the correct headers for your adapter DLL you can use the tool javah shipped with the JDK. This tool will generate the headers to be implemented from your Java code.
For further information the documentation of JNI will cover all questions about interaction with the JVM from native code. http://docs.oracle.com/javase/7/docs/technotes/guides/jni/