此例示范了不适用JNI默认的接口绑定规则来实现C/C++方法的调用,此处称之为“动态注册”。
转自:http://www.open-open.com/lib/view/open1324909652374.html
经过几天的努力终于搞定了android JNI部分,下面将我的这个小程序和大家分享一下。android JNI是连接android Java部分和C/C++部分的纽带,完整使用JNI需要Java代码和C/C++代码。其中C/C++代码用于生成库文件,Java代码用于引用C /C++库文件以及调用C/C++方法。
android Java部分代码:
jnitest.java
package com.hello.jnitest;
import android.app.Activity;
import android.os.Bundle;
public class jnitest extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Nadd test = new Nadd();
setTitle("The Native Add Result is "+String.valueOf(test.nadd(10, 20)));
}
}
Nadd.java
package com.hello.jnitest;
public class Nadd {
static {
System.loadLibrary("hello_jni");
}
public native int nadd(int a, int b);
}
android C/C++部分代码:
#define LOG_TAG "hello-JNI"
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <assert.h>
#include "jni.h"
#include "JNIHelp.h"
#include "android_runtime/AndroidRuntime.h"
static jint com_hello_jnitest_jnitest_nadd(JNIEnv *env, jobject obj, jint a, jint b)
{
return (a * b);
}
static JNINativeMethod gMethods[] = {
{"nadd", "(II)I", (void *)com_hello_jnitest_jnitest_nadd},
};
static int register_android_test_hello(JNIEnv *env)
{
return android::AndroidRuntime::registerNativeMethods(env, "com/hello/jnitest/Nadd", gMethods, NELEM(gMethods));
}
jint JNI_OnLoad(JavaVM *vm, void *reserved)
{
JNIEnv *env = NULL;
if (vm->GetEnv((void **)&env, JNI_VERSION_1_4) != JNI_OK) {
printf("Error GetEnv\n");
return -1;
}
assert(env != NULL);
if (register_android_test_hello(env) < 0) {
printf("register_android_test_hello error.\n");
return -1;
}
return JNI_VERSION_1_4;
}
LOCAL_PATH := $(call my-dir) include $(CLEAR_VARS) LOCAL_PRELINK_MODULE := false LOCAL_SRC_FILES := \ com_hello_jnitest.cpp LOCAL_SHARED_LIBRARIES := \ libandroid_runtime LOCAL_MODULE := libhello_jni include $(BUILD_SHARED_LIBRARY)