Android NDK: Calling Java functions from C++

后端 未结 2 816
渐次进展
渐次进展 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.

    0 讨论(0)
  • 2021-02-06 04:11

    http://docs.oracle.com/javase/7/docs/technotes/guides/jni/spec/functions.html

    GetStaticMethodID

    jmethodID GetStaticMethodID(JNIEnv *env, jclass clazz, const char *name, const char *sig);

    Returns the method ID for a static method of a class. The method is specified by its name and signature.

    0 讨论(0)
提交回复
热议问题