import android.app.Activity; import android.os.Bundle; public class JNITest extends Activity { public native int plus (int x, int y);//这个是需用c语言实现的函数 /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); int x = plus(1, 2); android.util.Log.d("jni", String.valueOf(x)); } static { System.loadLibrary("mylib"); } }
#include <jni.h> #include "JNITest.h" #ifdef __cplusplus //最好有这个,否则被编译器改了函数名字找不到不要怪我 extern "C" { #endif JNIEXPORT jint JNICALL Java_org_eshock_jnitest_JNITest_plus( JNIEnv* env, jobject thiz, jint x, jint y ) { return x + y; } #ifdef __cplusplus } #endif
public class JNITest { public native int plus (int x, int y); }
/* 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: plus * Signature: (II)I */ JNIEXPORT jint JNICALL Java_JNITest_plus (JNIEnv *, jobject, jint, jint); #ifdef __cplusplus } #endif #endif
LOCAL_PATH := $(call my-dir) #LOCAL_PATH表示c源代码文件的位置 include $(CLEAR_VARS) LOCAL_MODULE := mylib #LOCAL_MODULE表示生成的共享库的名称 LOCAL_SRC_FILES := mylib.c #LOCAL_SRC_FILES代表c代码的文件 include $(BUILD_SHARED_LIBRARY)
(3) E:\workspace\jnitest>ndk-build NDK_MODULE_PATH=jni //输入命令ndk-build NDK_MODULE_PATH=jni
注意事项:如果ndk环境变量没有配置,需要配置ndk环境变量
变量名:NDK_MODULE_PATH
变量值:C:\android-ndk-r9b (根据安装路径进行调整)
添加到path路径: %NDK_MODULE_PATH%;
如果path路径下没有冒号,自己添加一个
点击下载源码