Commit a6c51b49 authored by Sylvain Berfini's avatar Sylvain Berfini 🎩

Use weak ref instead of global ref for listeners to prevent leaks

parent f78cac6b
...@@ -377,9 +377,16 @@ static {{return}} {{callbackName}}({{params}}) { ...@@ -377,9 +377,16 @@ static {{return}} {{callbackName}}({{params}}) {
return{{returnIfFail}}; return{{returnIfFail}};
} }
jclass jlistenerClass = (jclass) env->GetObjectClass(jlistener); jobject up = env->NewLocalRef((jobject)jlistener);
if (up == nullptr) {
bctbx_warning("{{callbackName}}() listener in weak reference has been destroyed");
return{{returnIfFail}};
}
jclass jlistenerClass = (jclass) env->GetObjectClass(up);
jmethodID jcallback = env->GetMethodID(jlistenerClass, "{{jname}}", "{{jparams}}"); jmethodID jcallback = env->GetMethodID(jlistenerClass, "{{jname}}", "{{jparams}}");
env->DeleteLocalRef(jlistenerClass); env->DeleteLocalRef(jlistenerClass);
env->DeleteLocalRef(up);
{{#jobjects}} {{#jobjects}}
jobject j_{{objectName}} = get{{className}}(env, (Linphone{{className}} *){{objectName}}, TRUE); jobject j_{{objectName}} = get{{className}}(env, (Linphone{{className}} *){{objectName}}, TRUE);
...@@ -494,7 +501,7 @@ JNIEXPORT void JNICALL Java_{{jniPackage}}{{className}}Impl_addListener(JNIEnv* ...@@ -494,7 +501,7 @@ JNIEXPORT void JNICALL Java_{{jniPackage}}{{className}}Impl_addListener(JNIEnv*
bctbx_error("Java_{{jniPackage}}{{className}}Impl_addListener's {{classCName}} C ptr is null!"); bctbx_error("Java_{{jniPackage}}{{className}}Impl_addListener's {{classCName}} C ptr is null!");
return; return;
} }
jobject listener = env->NewGlobalRef(jlistener); jobject listener = env->NewWeakGlobalRef(jlistener);
{{classCName}}Cbs *cbs = linphone_factory_create_{{factoryName}}_cbs(nullptr); {{classCName}}Cbs *cbs = linphone_factory_create_{{factoryName}}_cbs(nullptr);
{{cPrefix}}_cbs_set_user_data(cbs, listener); {{cPrefix}}_cbs_set_user_data(cbs, listener);
{{#callbacksList}} {{#callbacksList}}
...@@ -518,7 +525,7 @@ JNIEXPORT void JNICALL Java_{{jniPackage}}{{className}}Impl_removeListener(JNIEn ...@@ -518,7 +525,7 @@ JNIEXPORT void JNICALL Java_{{jniPackage}}{{className}}Impl_removeListener(JNIEn
if (env->IsSameObject(listener, jlistener)) { if (env->IsSameObject(listener, jlistener)) {
{{cPrefix}}_cbs_set_user_data(cbs, nullptr); {{cPrefix}}_cbs_set_user_data(cbs, nullptr);
{{cPrefix}}_remove_callbacks(cptr, cbs); {{cPrefix}}_remove_callbacks(cptr, cbs);
env->DeleteGlobalRef(listener); env->DeleteWeakGlobalRef(listener);
break; break;
} }
} }
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment