I am using TextureView and Vulkan to draw 3D models. I get the surface from the TextureView and pass it to the native side to render.
I need to support multiple TextureView to render different 3D models simultaneously, but I find out that my native .so library is only loaded once per process, suitable for memory saving.
So I think I need a global std::map in jni to hold different c++ objects. Every TextureView has an id and could use its id to find its c++ objects.
I was planning to code like this.
#include <jni.h>
#include <string>
#include <map>
#include <android/native_window_jni.h>
#include <android/asset_manager_jni.h>
std::unique_ptr<std::map<jint, MiuiVkWidgetApp*>> mVkWidgetAppMapUniquePtr;
extern "C" JNIEXPORT jboolean JNICALL
Java_com_miui_vkwidget_MiuiVkTextureView_nativeInitVkWidgetApp(JNIEnv* env, jobject /* this */, jint id) {
...
if (!mVkWidgetAppMapUniquePtr) {
mVkWidgetAppMapUniquePtr.reset(new std::map<jint, MiuiVkWidgetApp*>());
}
...
return true;
}
extern "C" JNIEXPORT void JNICALL
Java_com_miui_vkwidget_MiuiVkTextureView_nativeDestroyVkWidgetApp(JNIEnv* /* env */,
jobject /* this */, jint id) {
mVkWidgetAppMapUniquePtr.reset(nullptr);
...
}
But in https://developer.android.com/training/articles/perf-jni#local-and-global-references "Local and global reference," it says that "The only way to get non-local references is via the functions NewGlobalRef and NewWeakGlobalRef." But NewGlobalRef seems only to support java objects.
I assume how I create the global map may have some potential risks, such as memory leak(I call DestroyVkWidgetApp when TextureView is onDestroy)? I am curious on how to create a proper global map in jni to hold multiple c++ objects? Thanks!