1、准备步骤ubuntu下配置好java、gcc相关的环境。
2.编写java文件
class JniTest { private native String getLine(String prompt); public static void main(String args[]) { JniTest jnitest = new JniTest(); String input = jnitest.getLine("Type a line: "); System.out.println("User typed: " + input); } static { System.loadLibrary("JniTest"); } }
javac JniTest.java
javah -jni JniTest
/* DO NOT EDIT THIS FILE - it is machine generated */ #include <jni.h> /* Header for class JniTest */ #ifndef _Included_JniTest #define _Included_JniTest #ifdef __cplusplus extern "C" { #endif /* * Class: JniTest * Method: getLine * Signature: (Ljava/lang/String;)Ljava/lang/String; */ JNIEXPORT jstring JNICALL Java_JniTest_getLine (JNIEnv *JniEnv,jobject obj,jstring inputstr){ char outputstr[50]; int lenght = (*JniEnv)->GetStringLength(JniEnv,inputstr); printf("inputstr lenght= %d",lenght); printf("请输入一个字符串返回给java"); scanf("%s",outputstr); return (*JniEnv)->NewStringUTF(JniEnv,outputstr); } #ifdef __cplusplus } #endif #endif
6、如果配置了android NDK的环境,可以用android,mk来编译生成so,从androidNDK的sample里找到一份Android.mk文件,与生成的JniTest.c代码放入jni文件夹下。或者直接用第7步的gcc命令来生成
LOCAL_PATH := $(call my-dir) include $(CLEAR_VARS) LOCAL_MODULE := JniTest LOCAL_SRC_FILES := JniTest.c include $(BUILD_SHARED_LIBRARY)
gcc JniTest.c -I /home/guoshijie/下载/jdk1.8.0_111/include -I /home/guoshijie/下载/jdk1.8.0_111/include/linux -fPIC -shared -o libJniTest.so
8、执行class
因为生成的so并没有放入系统的lib库里,所以需要指定lib库路径
可以用如下命令指定当前命令行窗口的lib库路径
/home/guoshijie/test/testc/jni 下放的是生成的so
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/home/guoshijie/test/testc/jni
或者用
java -Djava.library.path=./jni JniTest
执行出的结果如下
guoshijie@guoshijie-virtual-machine:~/test/testc$ java -Djava.library.path=./jni JniTest inputstr lenght= 13请输入一个字符串返回给javaaaa User typed: aaa guoshijie@guoshijie-virtual-machine:~/test/testc$原文链接:https://www.f2er.com/ubuntu/356136.html