How to call java from c#?

How to call Java API from NDK C++ thread?

  • I want to call Java API from NDK C++ thread, but env->FindClass() return 0. But when I call Java API in main thread, it works well. I've already call AttachCurrentThread() in the thread, can anyone help me? Here is the source code: JAVA CODE: public class simple_test extends Activity { ... // This functin will be called in C++ public void PrintNdkLog(String slog) { Log.e(logTagNDK, slog); return; } } C++ CODE: static JavaVM* g_JavaVM = NULL; jobject getInstance(JNIEnv *env, jclass obj_class) { jmethodID c_id = env->GetMethodID(obj_class, "<init>", "()V"); jobject obj = env->NewObject(obj_class, c_id); return obj; } // JNI OnLoad JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM* vm, void* reserved) { g_JavaVM = jvm; return JNI_VERSION_1_6; } // Call JAVA API "PrintNdkLog" in this function void PrintNdkLog(char *lpLog) { if (g_JavaVM == NULL) return; JNIEnv *env = NULL; g_JavaVM->GetEnv((void**)&env, JNI_VERSION_1_6); if (env == NULL) return; jclass cls = env->FindClass("com/myndk/simple_test"); if (cls != 0) // **cls will be 0 when PrintNdkLog() is called in thread** { LOGE("FindClass error %p", cls); } else { jmethodID mid; jobject obj; obj = getInstance(env, cls); mid = env->GetMethodID(cls, "PrintNdkLog", "(Ljava/lang/String;)V"); if (mid != 0) { jstring jstrMSG = env->NewStringUTF(lpLog); env->CallVoidMethod(obj, mid, jstrMSG); } } } // Call JAVA API in thread static void* thread_test(void* ptr) { JNIEnv *envLocal; int status = g_JavaVM->GetEnv((void **) &envLocal, JNI_VERSION_1_6); if (status == JNI_EDETACHED) { status = g_JavaVM->AttachCurrentThread(&envLocal, NULL); if (status != JNI_OK) LOGE("AttachCurrentThread failed %d",status); } PrintNdkLog("bbb"); // This JAVA callback failed, and printed "FindClass error" } // Create thread int NdkThread(AFX_THREADPROC pfnThreadProc, LPVOID pParam, int nPriority) { PrintNdkLog("aaa"); // This JAVA callback runs well pthread_t pid; pthread_create(&pid, NULL, thread_test, pParam); }

  • Answer:

    I have solved it now. In NDK native thread, only can call static Java API. If you call env->FindClass(), it would trigger an exception. http://android.wooyd.org/JNIExample gived the detail info.

airun at Stack Overflow Visit the source

Was this solution helpful to you?

Related Q & A:

Just Added Q & A:

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.