How to call a c/c++ - function in a DLL from within Java |
|
How to use the JNI in an example:This example is based on the JNI-interface from the Java-JDK. Let's show an example to call a C-function from a java-program. For more informations about this, please have a look on the official site at SUN. In this example, we want to call a function f with the following signature: int f(int i, char *s). So, we first write a java-wrapper with this function: // // Java-example function wrapper // class j { native int f(int i, String s); static { System.loadLibrary("c_dll"); } }; In the loadLibrary is the name of the DLL we will create. Having this wrapper, we have to compile the class (javac) and then generate a c-header file with javah: javah -classpath . j This will result in the file j.h: /* DO NOT EDIT THIS FILE - it is machine generated */ #include <jni.h> /* Header for class j */ #ifndef _Included_j #define _Included_j #ifdef __cplusplus extern "C" { #endif /* * Class: j * Method: f * Signature: (ILjava/lang/String;)I */ JNIEXPORT jint JNICALL Java_j_f (JNIEnv *, jobject, jint, jstring); #ifdef __cplusplus } #endif #endif Now lets implement a simple f function in C: // This is the C-part of the JNI-example #include "j.h" // This is the function called by the java-program JNIEXPORT jint JNICALL Java_j_f (jEnv, jObj, i, s) JNIEnv *jEnv; jobject jObj; jint i; jstring s; { /* Obtain a C-copy of the Java string */ const char *str = (*jEnv)->GetStringUTFChars(jEnv, s, 0); /* process the string */ printf("The string got by parameter from the java-program is :%s:\n", str); printf("The int got by parameter from the java-program is :%d:\n", i); /* Now we are done with str */ (*jEnv)->ReleaseStringUTFChars(jEnv, s, str); return i*i; // Return to java } Compile this function to a DLL under Windows (all this would also work on SUN, LINUX and so on with some changes in the compile-line) cl c_dll.c -I %JDKPATH%\include -I %JDKPATH%\include\win32 /link /DLL /out:c_dll.dll No a little java-main program to call the function f in the class j: import j; class jmain { public static void main(String args[]) { j ccall = new j(); System.out.println("Starting java-program"); System.out.println("Return from C-program: " + ccall.f(9, "Hello")); } }; If you put all this together and run the java-program, you will get the following output: Starting java-program The string got by parameter from the java-program is :Hello: The int got by parameter from the java-program is :9: Return from C-program: 81 The first step is done. Now, perhaps you need other types like double, other java-classes and so on. This is described at SUN, please have a look on these pages. For you, here the code-example to download: j2c.zip. If you find errors in this code or have comments on it, please tell me at source @ stueben.com |
|
| Comments are welcome | | |