简体   繁体   中英

How do I use a global reference across JNI calls

I have to use assetmanager in Android to open some files. I am using the Assetmanager to open a lua file. To that end, I create a luastate in an init function in JNI using AAssetmanager. I then use this luastate to call functions in my lua file. However, I am running an image processing application that would need to keep opening and closing this luastate for every frame which slows me down.

I am currently doing this -

JNIEXPORT jstring JNICALL
Java_com_torch_torchdemo_TorchDemo_callTorch( JNIEnv* env,
                                            jobject thiz,
                                            jobject assetManager) {
// get native asset manager

static jobject globalManager = env->NewGlobalRef(assetManager);

AAssetManager* manager = AAssetManager_fromJava(env, globalManager);
assert( NULL != manager);
lua_State *L = initstate(manager)
char file[] = "main.lua";
int ret;
long size = android_asset_get_size(file);

lua_getglobal(L,"test_func");
return nev->NewStringUTF(buffeR);
}

After this, I have no idea how to use the globalManager object in another jni function, one that I would call repeatedly. The one above would be called only once. I have tried directly using globalManager in another function but that gives me the error that globalManager was not defined in this scope. I cannot find any tutorials on how to use the global references either. The ones I found directly use the global object or class. That gives me an error in my case.

I have tried directly using globalManager in another function but that gives me the error that globalManager was not defined in this scope.

Your question is actually about the concept of global variables in C rather than global JNI references. You defined a static variable of type jobject called globalManager in the function Java_com_torch_torchdemo_TorchDemo_callTorch . That means that the variable keeps its value across multiple invocations of the function, but it still isn't defined globally. You can only access it from within the function. To use it in other functions, you have to define the variable globally, like this:

// define it as a global variable
static jobject globalManager;

JNIEXPORT jstring JNICALL Java_com_torch_torchdemo_TorchDemo_callTorch(JNIEnv* env, jobject thiz, jobject assetManager) {
    // get native asset manager
    globalManager = env->NewGlobalRef(assetManager);

    // ...
}

If you also want to access the variable from other sourcefiles, you have to use an extern declaration there and drop the static modifier in this file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM