Skip to content Skip to sidebar Skip to footer

Android Ndk: Calling Java Functions From C++

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 Androi

Solution 1:

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:

publicstaticvoidlog(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.

Solution 2:

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.

Post a Comment for "Android Ndk: Calling Java Functions From C++"