参考资料:
主要参考资料1
程序流程貌似是TestWordJni.class调用WordJni.class,WordJni.class调用libWordJni.so。因为我把其他文件(.java .h .c)删了都没事,WordJni.class不能删。
1.创建.java文件
import java.util.*;
public class WordJni{
public native String print(String content);
static
{
System.loadLibrary("WordJni");
}
}
2.[hadoop@Master jni]$ javac WordJni.java
3.生成.h文件[hadoop@Master jni]$ javah -jni WordJni
/* DO NOT EDIT THIS FILE - it is machine generated */
#include
/* Header for class WordJni */
#ifndef _Included_WordJni
#define _Included_WordJni
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: WordJni
* Method: print
* Signature: (Ljava/lang/String;)Ljava/lang/String;
*/
JNIEXPORT jstring JNICALL Java_WordJni_print
(JNIEnv *, jobject, jstring);
#ifdef __cplusplus
}
#endif
#endif
4.编写自己的C文件,注意:.c文件函数的名称,返回值都要和生成的.h文件相同,不然会出现java.lang.UnsatisfiedLinkError错误
#include
#include
#include
#include "WordJni.h"
JNIEXPORT jstring JNICALL
Java_WordJni_print(JNIEnv *env,jobject obj, jstring content)
{
char buf[128];//注c使用(*env),c++使用env
const jbyte *str = (const jbyte *)(*env)->GetStringUTFChars(env,content, JNI_FALSE);
strcpy(buf, str);
strcat(buf, "----copy that");
printf("%s\n",buf);
(*env)->ReleaseStringUTFChars(env, content, (const char *)str );
return (*env)->NewStringUTF(env, buf);
}
5.编译,生成库文件
[hadoop@Master jni]$ gcc -I/usr/java/jdk1.6.0_31/include -I/usr/java/jdk1.6.0_31/include/linux -fPIC -shared -o libWordJni.so WordJni.c
6.编写调用程序TestWordJni.java
public class TestWordJni {
public static void main(String argv[]) {
new TestWordJni();
}
public TestWordJni() {
new WordJni().print("Hello,World !"); //调用TestJni的原生函数print
}
}
7.生成.class文件
[hadoop@Master jni]$ javac TestWordJni.java
8.执行
[hadoop@Master jni]$ java -Djava.library.path='.' TestWordJni
9。结果
Hello,World !----copy that