step 1 :
cd /home/alex/jni
vi Test.java
public class Test {
static {
//System.loadLibrary("Test.so");
System.load("/home/alex/jni/Test.so");
}
public native String getinfo();
public static void main(String... args) {
String info = new Test().getinfo();
System.out.println(info);
}
}
step 2 :
javac Test.java
step 3 :
javah -jni Test
step 4 :
cat Test.h
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class Test */
#ifndef _Included_Test
#define _Included_Test
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: Test
* Method: getinfo
* Signature: ()Ljava/lang/String;
*/
JNIEXPORT jstring JNICALL Java_Test_getinfo
(JNIEnv *, jobject);
#ifdef __cplusplus
}
#endif
#endif
step 5 :
vi Test.c
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "jni.h"
JNIEXPORT jstring JNICALL Java_Test_getinfo(JNIEnv *env, jobject jobj) {
jstring answer;
char *msg = strdup("hello the world!");
answer = (*env)->NewStringUTF(env, msg);
free(msg);
return answer;
}
step 6 :
gcc -shared -fPIC Test.c -o Test.so -I/usr/lib/jvm/java-1.6.0-openjdk-1.6.0.0.x86_64/include/ -I/usr/lib/jvm/java-1.6.0-openjdk-1.6.0.0.x86_64/include/linux/
step 7 :
java Test
output :
hello the world!
关于javah的补充:
1. cd到你Android工程的bin/classes目录下
hejinlai_iMac:classes hejinlai$ pwd
/Users/hejinlai/Workspace/Android/SoundTouchDemo/bin/classes
这个是非常关键的,之所以错误,就是因为没有进入到这个目录下。很显然这个目录下面有一目录,这个目录就是你包名的顶级目录,一般来说都是com目录:
hejinlai_iMac:classes hejinlai$ ls -l
total 0
drwxr-xr-x 3 hejinlai staff 102 Jun 19 11:32 com
2. 然后执行 javah 包名.类名
注意包名一定要完整,用 . 隔开,后面的是类的名字,不带任何后缀。
hejinlai_iMac:classes hejinlai$ javah com.example.soundtouchdemo.JNISoundTouch
hejinlai_iMac:classes hejinlai$ ls -l
total 8
drwxr-xr-x 3 hejinlai staff 102 Jun 19 11:32 com
-rw-r--r-- 1 hejinlai staff 1918 Jun 19 14:49 com_example_soundtouchdemo_JNISoundTouch.h
hejinlai_iMac:classes hejinlai$
总结:在执行javah的时候,一定要确保在正确的目录下,javah后面的参数要是 包名.类名