原文地址
jni helper源码
- 来自cocos 3.8,头文件
“`
ifndef ANDROID_JNI_HELPER_H
define ANDROID_JNI_HELPER_H
include
include
typedef struct JniMethodInfo_ {
JNIEnv * env;
jclass classID;
jmethodID methodID;
} JniMethodInfo;
class JniHelper {
public:
static void setJavaVM(JavaVM *javaVM);
static JavaVM* getJavaVM();
static JNIEnv* getEnv();
static bool setClassLoaderFrom(jobject activityInstance); static bool getStaticMethodInfo(JniMethodInfo &methodinfo,const char *className,const char *methodName,const char *paramCode); static bool getMethodInfo(JniMethodInfo &methodinfo,const char *paramCode); static jmethodID loadclassMethod_methodID; static jobject classloader;
private:
static JNIEnv* cacheEnv(JavaVM* jvm);
static bool getMethodInfo_DefaultClassLoader(JniMethodInfo &methodinfo,const char *paramCode); static JavaVM* _psJavaVM;
};
endif // ANDROID_JNI_HELPER_H
“`
- .cpp
“`
include “JniHelper.h”
include “dlog.h”
include
include
include
用法
- 在jni onload里设置jvm
“`
JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM* vm,void* reserved) {
// other code
// …
JniHelper::setJavaVM(vm); return JNI_VERSION_1_4;
}
“`
- 在java新增一native方法,参数为context。在loadLibrary之后,在合适的地方调用该方法
“`
public native static int nativeInit(Context context);
在这个native的实现里,调用JniHelper::setClassLoaderFrom(obj);
jint xxx(JNIEnv* env,jclass clazz,jobject obj) {
JniHelper::setClassLoaderFrom(obj);
return 0;
}
“`
- 用法举例
int getDPIJNI()
{
JniMethodInfo t;
jint ret = -1;
if (JniHelper::getStaticMethodInfo(t,"org/cocos2dx/lib/Cocos2dxHelper","getDPI","()I")) {
ret = t.env->CallStaticIntMethod(t.classID,t.methodID);
t.env->DeleteLocalRef(t.classID);
}
return ret;
}