public class Test {
static {
System.loadLibrary("Hello");
}
public native void output();
public static void main(String [] args){
System.out.println(System.getProperty("java.library.path"));
Test test = new Test();
test.output();
}
}
javac Test.java
javah Test
生成
/* DO NOT EDIT THIS FILE - it is machine generated */
#include
/* Header for class Test */
#ifndef _Included_Test
#define _Included_Test
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: Test
* Method: output
* Signature: ()V
*/
JNIEXPORT void JNICALL Java_Test_output
(JNIEnv *, jobject);
#ifdef __cplusplus
}
#endif
#endif
根据生成的Test.h 中的JAVA_Test_output 的声明 ,写相应的C实现#include
#include
JNIEXPORT void JNICALL Java_Test_output(JNIEnv * jnienv, jobject job){
printf("Hello,World!!!
");
}
用gcc 编译生成相应的库,在windows 以dll 结尾,而在linux 是以.so 结尾,且以lib 开头
如 System.loadLibrary("Hello");
在windows 上要有Hello.dll 文件, 而在linux 上要有libHello.so 在 System.getProperty("java.library.path") 相应的目录
而在linux 下生成.so 文件,
用这个命令gcc -shared -fPIC Test.c -o libHello.so
把libHello.so 移到 System.getProperty("java.library.path")目录下