This program has been written for a long time, but it has encountered many small problems. Today, the program is running.
1. Write the Java source program
class HelloWorld { private native void print(); public static void main(String[] args) { new HelloWorld().print(); } static { System.loadLibrary("HelloWorld"); } }
The local function is print. in linux, the library file should be libHelloWorld. so.
2. compile and generate the header file
javac HelloWorld.javajavah HelloWorld
The generated header file is:
/* DO NOT EDIT THIS FILE - it is machine generated */#include <jni.h>/* Header for class HelloWorld */#ifndef _Included_HelloWorld#define _Included_HelloWorld#ifdef __cplusplusextern "C" {#endif/* * Class: HelloWorld * Method: print * Signature: ()V */JNIEXPORT void JNICALL Java_HelloWorld_print (JNIEnv *, jobject);#ifdef __cplusplus}#endif#endif
3. C program
#include <jni.h>#include <stdio.h>#include "HelloWorld.h"JNIEXPORT void JNICALL Java_HelloWorld_print(JNIEnv *env, jobject obj){printf("i am linc !!!\n");return;}
4. Compile the make file (this file is called makefile without a suffix)
libHelloWorld.so:HelloWorld.ogcc -rdynamic -shared -o libHelloWorld.so HelloWorld.oHelloWorld.o:HelloWorld.c HelloWorld.hgcc -c HelloWorld.c -I./ -I/usr/java/jdk1.6.0_25/include -I/usr/java/jdk1.6.0_25/include/linux
5. Run makefile. As long as it is in the makefile directory, make and press Enter.
At this time, libHelloWorld. so will be generated. In principle, put this so file in the directory of the java. class file, and you will be able to run normally.
But I failed.
Error:Java. lang. UnsatisfiedLinkError: no HelloWorld in java. library. path
The final solution is as follows:
public class LibPath {public static void main(String args[]){ System.out.println("Linc"); System.out.println(System.getProperty("java.library.path")); } }
Print out the lib directory. I used/usr/java/jdk1.6.0 _ 25/jre/lib/i386/server.
Then put the so file into it, and it will be OK.
I also encountered the problem of no permission. I used root to change the permission of this directory.
Now we can continue to learn about JNI !!!