Android NDK: calling Java functions from C ++

I am very new to JNI and I am trying to understand how some things work before I port the C ++ iOS code to it. I managed to get one of the NDK samples running in the Android studio, and I see how Java can call C ++ functions.

I searched and made pieces of code, but I was not able to get it to work in my specific implementation.

Just to test how everything works, I created a simple text log function in java and I try to call it from my own code, but I am having problems.

Here is my java function:

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

And 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); } 

From what I saw with different examples, this should work, but it causes an error:

 29835-29849/com.android.gl2jni A/libc﹕ Fatal signal 11 (SIGSEGV) at 0x00000000 (code=1), thread 29849 (Thread-17371) 

Did I miss something?

EDIT:

I changed it to GetStaticMethodID. But after registering the progress of the function, I found that the failed line:

 g_JavaVM->GetEnv((void**)&env, JNI_VERSION_1_6); 

I believe g_JavaVM is set to static JavaVM* g_JavaVM = NULL; and then never starts again. I assume I need to set this variable, but how?

+5
source share
2 answers

Part of my problem was that I did not initialize JavaVM. The other part was that I used C ++, but I tried to use the C functions.

Work code:

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); 

Hope this helps other people with the same problem.

+7
source

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 identifier for the static class method. The method is determined by its name and signature.

+2
source

Source: https://habr.com/ru/post/1213781/


All Articles