JNI開発基礎シリーズ-JNIメソッド動的登録

4368 ワード

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 
#include 
#include "add.h"
#include 

#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
"
)
; return -1; } assert(env != NULL); registerNatives(env); return JNI_VERSION_1_4; }