Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between "jobject" & "jclass" in C++ NDK

I did 2 different implementations from tutorials I followed and I noticed the parameters are a little different for each one, 1 parameter is jclass and the other is jobject I don't use these parameters at all, but I tried experimenting and switching them from jclass to jobject and jobject to jclass and I noticed everything still works as expected so I'm not sure what exactly jobject and jinstance do exactly, also if my method is not using either of these parameters why are they required ? and can someone please provide the correct declaration of these methods in my java class i'm unsure if I did it right

JNIEXPORT void JNICALL Java_org_cocos2dx_cpp_AppActivity_pauseSounds(JNIEnv* env, jclass thiz);

JNIEXPORT jstring JNICALL Java_org_cocos2dx_cpp_AppActivity_score(JNIEnv *env, jobject instance);
like image 421
isJulian00 Avatar asked May 21 '19 03:05

isJulian00


1 Answers

Generally,

  • if the JNI function arguments have jclass, then this JNI function corresponds to the Java side class method (the native methods declared with "static"). jclass is a reference to the current class.
  • if the JNI function arguments have jobject, then this JNI function corresponds to the Java side instance method (the native methods declared without "static"). jobject is a reference to the current instance.

Specifically,

JNIEXPORT void JNICALL Java_org_cocos2dx_cpp_AppActivity_pauseSounds(JNIEnv* env, jclass thiz);

corresponds to the static native method (class method) on your Java side, i.e.

package org.cocos2dx.cpp

class AppActivity{
    public static native void pauseSounds();
}

While below JNI method

JNIEXPORT jstring JNICALL Java_org_cocos2dx_cpp_AppActivity_score(JNIEnv *env, jobject instance);

corresponds to the native method (instance method) on your Java side, i.e.

package org.cocos2dx.cpp

class AppActivity{
   public native String score();
}

if my method is not using either of these parameters why are they required ?

These parameters are auto generated and will be used by JNI if needed, for example, in the case that you need to call back the Java side class methods, you need something like below (()V" is the method JNI signature):

jmethodID staticMethod = env->GetStaticMethodID(clazz, "pauseSounds", "()V");

in the case that you need to call back the Java side instance methods, you need something like below(()Ljava/lang/String;" is the method JNI signature):

env->CallObjectMethod(instance, "score", "()Ljava/lang/String;");
like image 192
shizhen Avatar answered Sep 20 '22 17:09

shizhen