我有一个JNI问题,我希望有人可以帮我解决。
我试图从本机线程调用一个名为LUSOutputJNI的Java类的构造函数
它一直在这个特定类的FindClass(...)上失败。
以下是代码:
LOGE("1");
JNIEnv *env = NULL;
LOGE("2");
int res = -1;
res = g_vm->AttachCurrentThread(&env, NULL);
if(env == NULL)
{
LOGE("env is NULL, AttachCurrentThread failed");;
}
if(res >= 0)
LOGE("AttachCurrentThread was successful");
jclass clazz = NULL;
jmethodID cid;
jclass clazzESEngine;
jmethodID callbackid;
jobject jCoreOut;
static jfieldID fid_ActionState = NULL;
static jfieldID fid_nSpeed = NULL;
static jfieldID fid_nType = NULL;
static jfieldID fid_nInProcess = NULL;
static jfieldID fid_nX = NULL;
static jfieldID fid_nY = NULL;
LOGE("3");
static const char* const ECOClassName = "lus/android/sdk/LUSOutputJNI";
//static const char* const ECOClassName = "android/widget/TextView";
clazz = env->FindClass(ECOClassName);
if (clazz == NULL) {
LOGE("Can't find class LUSOutputJNI");
}
else
LOGE("lus/android/sdk/LUSOutputJNI was found, YEY!!");
LOGE("4");
cid = env->GetMethodID(clazz,"<init>", "()V");
LOGE("5");
jCoreOut = env->NewObject(clazz, cid);
LOGE("6");
以下是失败时的logcat输出:
E/lusCore_JNI( 3040): 1
E/lusCore_JNI( 3040): 2
E/lusCore_JNI( 3040): AttachCurrentThread was successful
E/lusCore_JNI( 3040): 3
E/lusCore_JNI( 3040): Can't find class LUSOutputJNI
E/lusCore_JNI( 3040): 4
W/dalvikvm( 3040): JNI WARNING: JNI method called with exception raised
观察:
我做错了什么?
非常感谢帮助:)
感谢您的时间,
伊达
答案 0 :(得分:6)
找到答案\在这里解决。 (寻找FAQ:“FindClass没找到我的班级” JNI tips)
我基本上将全局引用保存到所需的jclass对象中
然而,为了编译代码,却必须克服C / JNI和C ++ / JNI之间的一些邪恶的JNI变化。
这就是我如何编译和工作NewGlobalRef。
jclass localRefCls = env->FindClass(strLUSClassName);
if (localRefCls == NULL) {
LOGE("Can't find class %s",strLUSCoreClassName);
return result;
}
//cache the EyeSightCore ref as global
/* Create a global reference */
clazzLUSCore = (_jclass*)env->NewGlobalRef(localRefCls);
/* The local reference is no longer useful */
env->DeleteLocalRef(localRefCls);
/* Is the global reference created successfully? */
if (clazzLUSCore == NULL) {
LOGE("Error - clazzLUSCore is still null when it is suppose to be global");
return result; /* out of memory exception thrown */
}
我希望这对任何人都有帮助。
答案 1 :(得分:2)
要获得有关最新信息的更多信息(它将记录到stderr,而不是LOGE,我不知道如何更改),您可以添加一些异常打印 - 您可以更改此信息:
//static const char* const ECOClassName = "android/widget/TextView";
clazz = env->FindClass(ECOClassName);
if (clazz == NULL) {
LOGE("Can't find class LUSOutputJNI");
}
else
LOGE("lus/android/sdk/LUSOutputJNI was found, YEY!!");
对此:
//static const char* const ECOClassName = "android/widget/TextView";
clazz = env->FindClass(ECOClassName);
if (clazz == NULL) {
LOGE("Can't find class LUSOutputJNI");
jthrowable exc = env->ExceptionOccurred();
if(exc)
{
env->ExceptionDescribe();
env->ExceptionClear();
}
}
else
LOGE("lus/android/sdk/LUSOutputJNI was found, YEY!!");