1)首先写HelloWorld的java类
class HelloWorld {
static {
System.loadLibrary("HelloWorld");
}
private native void print();
public static void main(String[] args) {
new HelloWorld().print();
}
}
2)编译 生成 .h 文件
javac HelloWorld.java
javah -jni HelloWorld
如果找不到类添加参数 -classpath ./
javah -classpath ./ -jni HelloWorld
HelloWorld.h生成如下
/
* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/ * Header for class HelloWorld */
#include <jni.h>
/ * Header for class HelloWorld */
#ifndef _Included_HelloWorld
#define _Included_HelloWorld
#ifdef __cplusplus
extern "C" {
#endif
/ *
* Class: HelloWorld
* Method: print
* Signature: ()V
*/
JNIEXPORT void JNICALL Java_HelloWorld_print
(JNIEnv *, jobject);
#define _Included_HelloWorld
#ifdef __cplusplus
extern "C" {
#endif
/ *
* Class: HelloWorld
* Method: print
* Signature: ()V
*/
JNIEXPORT void JNICALL Java_HelloWorld_print
(JNIEnv *, jobject);
#ifdef __cplusplus
}
#endif
#endif
}
#endif
#endif
然后编写 HelloWorld.c 文件
#include <jni.h>
#include <stdio.h>
#include "HelloWorld.h"
#include <stdio.h>
#include "HelloWorld.h"
JNIEXPORT void JNICALL
Java_HelloWorld_print(JNIEnv *env, jobject obj)
{
printf("Hello World In C !\n");
return;
}
Java_HelloWorld_print(JNIEnv *env, jobject obj)
{
printf("Hello World In C !\n");
return;
}
3)编译c文件
gcc -shared -static -lc -I/opt/jdk/jdk1.6.0_21/include -I/opt/jdk/jdk1.6.0_21/include/linux HelloWorld.c -o libHelloWorld.so
其中 libHelloWorld.so 为链接库 前缀一定是lib 而不是 HelloWorld
-I跟单是两个jdk目录下面的头文件位置
4)运行
java HelloWorld
如果找不到类添加参数 -classpath ./
java -classpath ./ HelloWorld