整个实现过程可以分为五步来完成:
1)写一个声明了native的Java文件:
package example;
public class TestJNI {
static {
System.loadLibrary( " test " );
}
public native String getNameCPP();
}
public class TestJNI {
static {
System.loadLibrary( " test " );
}
public native String getNameCPP();
}
2) 使用javah产生对应的CPP头文件:
命令:javah -classpath <path> -jni example.TestJNI -d <out_dir>
生成的头文件example_TestJNI.h如下:
/**/
/* DO NOT EDIT THIS FILE - it is machine generated */
#include < jni.h >
/**/ /* Header for class example_TestJNI */
#ifndef _Included_example_TestJNI
#define _Included_example_TestJNI
#ifdef __cplusplus
extern " C " {
#endif
/**/ /*
* Class: example_TestJNI
* Method: getNameForCPP
* Signature: ()Ljava/lang/String;
*/
JNIEXPORT jstring JNICALL Java_example_TestJNI_getNameForCPP
(JNIEnv * , jobject);
#ifdef __cplusplus
}
#endif
#endif
#include < jni.h >
/**/ /* Header for class example_TestJNI */
#ifndef _Included_example_TestJNI
#define _Included_example_TestJNI
#ifdef __cplusplus
extern " C " {
#endif
/**/ /*
* Class: example_TestJNI
* Method: getNameForCPP
* Signature: ()Ljava/lang/String;
*/
JNIEXPORT jstring JNICALL Java_example_TestJNI_getNameForCPP
(JNIEnv * , jobject);
#ifdef __cplusplus
}
#endif
#endif
3)实现对应的CPP代码:
#include
"
example_TestJNI.h
"
#include < string >
JNIEXPORT jstring JNICALL Java_example_TestJNI_getNameForCPP
(JNIEnv * env, jobject)
{
// TODO 可以在此调用其他的代码
std:: string strName = " Tower " ;
return env -> NewStringUTF(strName.c_str());
}
#include < string >
JNIEXPORT jstring JNICALL Java_example_TestJNI_getNameForCPP
(JNIEnv * env, jobject)
{
// TODO 可以在此调用其他的代码
std:: string strName = " Tower " ;
return env -> NewStringUTF(strName.c_str());
}
4) 编译CPP代码
命 令:g++ -o libtest.so -shared -I<include_path> -I<java_home>/include -I<java_home>/include/linux example_TestJNI.cpp
5)执行
package example;
public class Test {
public static void main(String[] args) {
TestJNI test = new TestJNI();
System. out .println( " Hello " + test.getNameForCPP());
}
}
public class Test {
public static void main(String[] args) {
TestJNI test = new TestJNI();
System. out .println( " Hello " + test.getNameForCPP());
}
}
export LD_EXPORT_PATH=<so_path>
java -cp <path> -Djava.library.path=<so_path> example.Test
输出:Hello Tower