JNI开发基础系列-JNI方法动态注册

来源:互联网 发布:网络延迟检测 编辑:程序博客网 时间:2024/05/28 06:04

JNI方法动态注册

java中创建FileUtils.java

package com.cool.ndktest2;/** * Created by cool on 2017/8/17. */public class FileUtils {    public native void diff(String path,String pattrn,int num);}

c中

//// Created by cool on 2017/8/16.//#include "com_cool_ndktest2_MainActivity.h"#include <string.h>#include <android/log.h>#include "add.h"#include <assert.h>#define TAG "399"#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR,TAG,__VA_ARGS__)# define NELEM(x) ((int) (sizeof(x) / sizeof((x)[0])))JNIEXPORT void JNICALL native_diff        (JNIEnv *env, jclass clazz, jstring path, jstring pattern_Path, jint file_num){    LOGE("JNI begin 动态注册的方法 ");}static const JNINativeMethod gMethods[] = {        {                "diff","(Ljava/lang/String;Ljava/lang/String;I)V",(void*)native_diff        }};static int registerNatives(JNIEnv* engv){    LOGE("registerNatives begin");    jclass  clazz;    clazz = (*engv) -> FindClass(engv, "com/cool/ndktest2/FileUtils");    if (clazz == NULL) {        LOGE("clazz is null");        return JNI_FALSE;    }    if ((*engv) ->RegisterNatives(engv, clazz, gMethods, NELEM(gMethods)) < 0) {        LOGE("RegisterNatives error");        return JNI_FALSE;    }    return JNI_TRUE;}JNIEXPORT jint JNI_OnLoad(JavaVM* vm, void* reserved){    LOGE("jni_OnLoad begin");    JNIEnv* env = NULL;    jint result = -1;    if ((*vm)->GetEnv(vm,(void**) &env, JNI_VERSION_1_4) != JNI_OK) {        LOGE("ERROR: GetEnv failed\n");        return -1;    }    assert(env != NULL);    registerNatives(env);    return JNI_VERSION_1_4;}
原创粉丝点击