NDK:动态注册方法

#include 
#include 

extern "C" JNIEXPORT jstring

JNIEXPORT  JNICALL stringFromJNI(
        JNIEnv *env,
        jobject /* this */) {
    std::string hello = "Hello from C++1";
    return env->NewStringUTF(hello.c_str());
}

#define JNIREG_CLASS "learn/yc/jnilearn/MainActivity"//指定类

static JNINativeMethod getMethods[] = {
        {"hello","()Ljava/lang/String;",(void *) stringFromJNI}
};

static int registerNativeMethods(JNIEnv * env, const char * className,
JNINativeMethod* gMethods, int numMethods)
{
    jclass  clazz;
    clazz = env->FindClass(className);
    if(clazz == NULL){
        return JNI_FALSE;
    }
    if(env->RegisterNatives(clazz,gMethods,numMethods)<0){
        return JNI_FALSE;
    }
    return JNI_TRUE;
}

static int registerNatives(JNIEnv * env){
    if(!registerNativeMethods(env,JNIREG_CLASS,getMethods,sizeof(getMethods)/sizeof(getMethods[0])))
        return JNI_FALSE;
    return JNI_TRUE;
}

JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM * vm, void * reserved){
    JNIEnv * env = NULL;
    jint result = -1;
    if(vm->GetEnv((void **)&env,JNI_VERSION_1_4) != JNI_OK){
        return result;
    }
    assert(env != NULL);
    if(!registerNatives(env)){
        return result;
    }
    result = JNI_VERSION_1_4;
    return result;
}


 

你可能感兴趣的:(NDK:动态注册方法)