Android NDK: Calling Java functions from C++

后端 未结 2 817
渐次进展
渐次进展 2021-02-06 03:21

I am very new to JNI and I am trying to figure out how certain things work before I port my C++ iOS code to it. I was successful in getting one of the NDK samples working in And

2条回答
  •  天涯浪人
    2021-02-06 04:04

    Part of my problem was that I didn't initialize The JavaVM. The other part was that I was using C++, but I was trying to use the C functions.

    The working code is:

    Java:

    public static void log(String s){
            Log.d("Native", s);
    }
    

    C++:

    void Log(std::string s){
    
        JNIEnv *env;
        g_JavaVM->GetEnv((void**)&env, JNI_VERSION_1_6);
    
        jstring jstr1 = env->NewStringUTF(s.c_str());
    
        jclass clazz = env->FindClass("com/android/gl2jni/GL2JNILib");
        jmethodID mid = env->GetStaticMethodID(clazz, "log", "(Ljava/lang/String;)V");
    
        jobject obj = env->CallStaticObjectMethod(clazz, mid, jstr1);
    }
    
    //In some initialization function with Environment variable
    
    env->GetJavaVM(&g_JavaVM);
    

    Hopefully this can help other people with the same problem.

提交回复
热议问题