Java 代码 TestJNI.java
public class TestJNI {
private native int testJniAdd(int v1, int v2);
public void test() {
System.out.println("The result: " + testJniAdd(2, 3));
}
public static void main(String[] args) {
TestJNI instance = new TestJNI();
instance.test();
}
static {
System.load("~/JNITest/libtestJniLib.so");
}
}
javah 生成 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: testJniAdd
* Signature: (II)I
*/
JNIEXPORT jint JNICALL Java_TestJNI_testJniAdd
(JNIEnv *, jobject, jint, jint);
#ifdef __cplusplus
}
#endif
#endif
TestJNI.c 代码实现
#include "TestJNI.h"
/*
* Class: TestJNI
* Method: testJniAdd
* Signature: (II)I
*/
JNIEXPORT jint JNICALL Java_TestJNI_testJniAdd
(JNIEnv * env, jobject obj, jint v1, jint v2) {
return v1 + v2;
}
在 Android NDK 下编译so
LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
LOCAL_MODULE := testJniLib
LOCAL_SRC_FILES := TestJNI.c
include $(BUILD_SHARED_LIBRARY)
在 Linux gcc 下编译so
#!/bin/sh
gcc -I '~/java/include' -I '~/java/include/linux' TestJNI.c -shared -o libtestJniLib.so