美文网首页
RegisterNatives

RegisterNatives

作者: CentForever | 来源:发表于2021-01-08 15:10 被阅读0次

    JNIUtil.c

    #include <stdlib.h>
    #include <string.h>
    #include <stdio.h>
    #include <jni.h>
    #include <assert.h>
    #define JNIREG_CLASS "com/losileeya/registernatives/JNIUtil"//指定要注册的类
    jstring call(JNIEnv* env, jobject thiz)
    {
        return (*env)->NewStringUTF(env, "动态注册JNI,居然可以把头文件删掉也不会影响结果,牛逼不咯");
    }
    jint sum(JNIEnv* env, jobject jobj,jint num1,jint num2){
        return num1+num2;
    }
    /**
    * 方法对应表
    */
    static JNINativeMethod gMethods[] = {
            {"stringFromJNI", "()Ljava/lang/String;", (void*)call},
            {"sum", "(II)I", (void*)sum},
    };
    
    /*
    * 为某一个类注册本地方法
    */
    static int registerNativeMethods(JNIEnv* env
            , const char* className
            , JNINativeMethod* gMethods, int numMethods) {
        jclass clazz;
        clazz = (*env)->FindClass(env, className);
        if (clazz == NULL) {
            return JNI_FALSE;
        }
        if ((*env)->RegisterNatives(env, clazz, gMethods, numMethods) < 0) {
            return JNI_FALSE;
        }
    
        return JNI_TRUE;
    }
    
    
    /*
    * 为所有类注册本地方法
    */
    static int registerNatives(JNIEnv* env) {
        return registerNativeMethods(env, JNIREG_CLASS, gMethods,
                                     sizeof(gMethods) / sizeof(gMethods[0]));
    }
    
    /*
    * System.loadLibrary("lib")时调用
    * 如果成功返回JNI版本, 失败返回-1
    */
    JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM* vm, void* reserved) {
        JNIEnv* env = NULL;
        jint result = -1;
    
        if ((*vm)->GetEnv(vm, (void**) &env, JNI_VERSION_1_4) != JNI_OK) {
            return -1;
        }
        assert(env != NULL);
    
        if (!registerNatives(env)) {//注册
            return -1;
        }
        //成功
        result = JNI_VERSION_1_4;
    
        return result;
    }
    

    JNIUtil

    public class JNIUtil {
        static {
            System.loadLibrary("RegisterNatives");//与build.gradle里面设置的so名字,必须一致
        }
    
        public static native String stringFromJNI();
        public static native int sum(int num1,int num2);
    }
    

    相关文章

      网友评论

          本文标题:RegisterNatives

          本文链接:https://www.haomeiwen.com/subject/tilfaktx.html