Reputation: 202
Please help to call java void method(non static) from C++, It simple sdl2 android project . I'am trynig many times but can't make it works:-(. CallVoidMethod always crashes.
C++ code:
JNIEnv* Android_JNI_GetEnv(void) {
JNIEnv *env;
int status = mJavaVM->AttachCurrentThread(&env, NULL);
if(status < 0) {
LOGE("failed to attach current thread");
return 0;
}
return env;
}
int Android_JNI_SetupThread(void) {
JNIEnv *env = Android_JNI_GetEnv();
pthread_setspecific(mThreadKey, (void*) env);
return 1;
}
jint JNI_OnLoad(JavaVM* vm, void* reserved)
{
JNIEnv *env;
mJavaVM = vm;
LOGI("JNI_OnLoad called");
if (mJavaVM->GetEnv((void**) &env, JNI_VERSION_1_4) != JNI_OK) {
LOGE("Failed to get the environment using GetEnv()");
return -1;
}
Android_JNI_SetupThread();
return JNI_VERSION_1_4;
}
void B_Init(JNIEnv* mEnv, jclass cls, jobject obj)
{
Android_JNI_SetupThread();
mActivityClass = (jclass)mEnv->NewGlobalRef(cls);
}
extern "C" void Java_org_libsdl_app_SDLActivity_nativeInitB(JNIEnv* env, jclass cls, jobject obj)
{
/* This interface could expand with ABI negotiation, calbacks, etc. */
B_Init(env, cls, obj);
}
void Java_org_libsdl_app_SDLActivity_nativeDemoInit()
{
JNIEnv* env = Android_JNI_GetEnv();
jclass cls;
jmethodID mid;
cls = env->FindClass("org/libsdl/app/SDLActivity");
mid = env->GetMethodID(cls, "displayInterstitial2", "()V");
**env->CallVoidMethod(cls, mid2);**
}
}
Java code(org/libsdl/app/SDLActivity):
/**
SDL Activity
**/
public class SDLActivity extends Activity {
public void displayInterstitial2() {
some code;
}
}
I'm trying next to simplify code
C++ code:
JNIEXPORT void JNICALL Java_org_libsdl_app_SDLActivity_nativeinitB(JNIEnv* env, jobject obj)
{
jclass clz = env->GetObjectClass(obj); // instead of FindClass
jmethodID mid = env->GetMethodID(clz, "displayInterstitial2", "()V");
// if(!mid) return; // method does not exist, should write some logs
env->CallVoidMethod(obj, mid);
}
and get error: No implementation for native Lorg/libsdl/app/SDLActivity;.nativeInitB:()V
Upvotes: 0
Views: 1728
Reputation: 10203
If you call native method from your activity, you can try this way:
JNIEXPORT void JNICALL Java_org_libsdl_app_SDLActivity_nativeDemoInit(JNIEnv* env, jobject obj){
jclass cls = (*env)->GetObjectClass(env,obj); // instead of FindClass
jmethodID mid = (*env)->GetMethodID(env, cls, "displayInterstitial2", "()V");
if(!mid) return; // method does not exist, should write some logs
(*env)->CallVoidMethod(env, obj, mid);
}
in Activity class:
public void displayInterstitial2(){
Log.d("call displayInterstitial2");
}
public native void nativeDemoInit();
Upvotes: 1