class SmartAttachCurrentThread
{
public:
SmartAttachCurrentThread(JavaVM *jvm, JNIEnv *env) : jvm(jvm), env(env)
{
//TODO: throw if jvm null?
jvm->AttachCurrentThread(&env, NULL);
}
~SmartAttachCurrentThread()
{
jvm->DetachCurrentThread();
}
private:
JNIEnv *env;
JavaVM *jvm;
};
我正在尝试设计一个智能类,该类为我附加当前的jni线程并自动分离,因此可以这样使用:
{
JNIEnv *env;
SmartAttachCurrentThread smartAttachCurrentThread(jvm, env);
jclass clazz;
clazz = env->FindClass("com/app/myapp/");
//call class method
//thread is detached here prevnting memory leak
}
但是AttachCurrentThread
里面SmartAttachCurrentThread
不会改变JNIEnv *env;
就行了
{
JNIEnv *env;
有什么好的解决方案?我真的需要这个类吗,或者我可以将它std::unique_lock<T>
用于T
做相同事情的某种类型?
您的类构造JNIEnv*
函数按值获取参数,这就是为什么env
不更新类外部变量的原因。您需要改为通过引用传递它,例如:
class SmartAttachCurrentThread
{
public:
SmartAttachCurrentThread(JavaVM *jvm, JNIEnv* &env) : jvm(jvm)
{
if (!jvm)
throw ...; // whatever you want
if (jvm->AttachCurrentThread(&env, NULL) != JNI_OK)
throw ...; // whatever you want
}
~SmartAttachCurrentThread()
{
jvm->DetachCurrentThread();
}
private:
JavaVM *jvm;
};
...
{
JNIEnv *env;
SmartAttachCurrentThread smartAttachCurrentThread(jvm, env);
// now you can use env as needed...
}
或者,通过指针传递它,例如:
class SmartAttachCurrentThread
{
public:
SmartAttachCurrentThread(JavaVM *jvm, JNIEnv **env) : jvm(jvm)
{
if (!jvm || !env)
throw ...; // whatever you want
if (jvm->AttachCurrentThread(env, NULL) != JNI_OK)
throw ...; // whatever you want
}
~SmartAttachCurrentThread()
{
jvm->DetachCurrentThread();
}
private:
JavaVM *jvm;
};
...
{
JNIEnv *env;
SmartAttachCurrentThread smartAttachCurrentThread(jvm, &env);
// now you can use env as needed...
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句