TestJNI.java
1 public class TestJNI { 2 3 static{ 4 System.load("/home/buyizhiyou/workspace/JNI/src/libTestJNI.so");//注意此处加载.so文件 5 } 6 public native String test(String inp);//此处需要声明 7 8 public static void main(String[] args){ 9 TestJNI j=new TestJNI(); 10 String ret=j.test("inputs"); 11 System.out.println(ret); 12 } 13 }
javah -jni TestJNI 生成TestJNI.h,这个文件不用自己改,如下:
/* DO NOT EDIT THIS FILE - it is machine generated */ #include <jni.h> /* Header for class TestJNI */ #ifndef _Included_TestJNI #define _Included_TestJNI #ifdef __cplusplus extern "C" { #endif /* * Class: TestJNI * Method: test * Signature: (Ljava/lang/String;)Ljava/lang/String; */ JNIEXPORT jstring JNICALL Java_TestJNI_test (JNIEnv *, jobject, jstring); #ifdef __cplusplus } #endif #endif
然后用c++实现JNICALL Java_TestJNI_test方法,注意c++类型和JNI类型的转换:
#include "TestJNI.h" #include<iostream> using namespace std; JNIEXPORT jstring JNICALL Java_TestJNI_test(JNIEnv * env, jobject, jstring inp) { char* s = (char*)env->GetStringUTFChars(inp, NULL); cout<<s<<endl; jstring ret = env->NewStringUTF("return"); return ret; }
编译c++成.so文件,注意指定头文件路径,因为需要用到jni.h, jni_md.h:
g++ TestJNI.cpp -I/usr/lib/jvm/java-8-oracle/include/linux/ -I/usr/lib/jvm/java-8-oracle/include/ -fPIC -shared -o libTestJNI.so
然后javac TestJNI.java编译,java TestJNI执行即可。