简体   繁体   中英

Calling static Java method from Android native c++ code

I have a static java function which I want to call from Native C++ Android code.

Java method :

package com.verizon.freebeesdk;

public class Session {
    public static void checkExpiry(String s){

        Log.d("CALLED FROM JNI",s);

    }
}

C++ code:

static JNIEnv* __getEnv(bool* attached)
{
JNIEnv* env = NULL;
*attached = false;
int ret = __java_vm->GetEnv((void**)&env, JNI_VERSION_1_4);
if (ret == JNI_EDETACHED) {
    if (0 != __java_vm->AttachCurrentThread(&env, NULL)) {
        return NULL;
    }
    *attached = true;
    return env;
}

if (ret != JNI_OK) {
    return NULL;
}

return env;
}

void __check_expiry(){

JNIEnv* env = NULL;
static bool __is_attached_1 = false;

if ((env = __getEnv(&__is_attached_1)) == NULL) {
    log_info("getEnv fail\r\n");
}
assert(!__is_attached_1);

jstring jstr = env->NewStringUTF("This string comes from JNI");
log_info("CHECK EXPIRY: %s ",env->GetStringUTFChars(jstr ,0));

jclass clazz = env->FindClass("com/verizon/freebeesdk/Session");
if(clazz == 0){
    log_info("This class not found");
}
jmethodID mid = env->GetStaticMethodID(clazz, "checkExpiry", "(Ljava/lang/String;)V");
env->CallStaticVoidMethod(clazz, mid, jstr);
}

Output :

I always get the statement "This class not found" and subsequently the error :

java.lang.NoClassDefFoundError: Class not found using the boot class loader; no stack trace available

The JNIEnv is set up properly as the first log statement prints properly "CHECK EXPIRY: This string comes from JNI "

Can someone kindly help me out ?

Thanks.

First of all, your title is not accurate since your problem (at least the one you are facing now) is not about calling the static function, but about finding the Session class.

Although your code for getting the class seems right, there might be other reasons the class cannot be found, such as class loader issue - take a look at the JNI documentation on that, and see if it helps: FAQ: Why didn't FindClass find my class?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM