简体   繁体   中英

Shared Library with JNI: how to maintain global variables?

I have written a shared library which is accessed via my linux-system and via a JNI-call from java.

That library should have a global ringbuffer which must be available in the JNI-method and in the other native methods.

I thought this won't be a problem, because when I access the SL from different programs, the global variables are always as they should.

But now, in my JNI-method, the global variables seem to be not initialized (they should as the program-flow forces it).

Here is my example:

ringbuf_t ringbuffer;

void internalMethod() {
    // this method is first called from system-program
    ringbuffer = ringbuf_new(5000);
}


JNIEXPORT jint JNICALL Java_example_read(JNIEnv *env, jobject This) {
    // this method is later called via JNI
    if (!ringbuffer) {
        LOGI("uhhh, why is that buffer not set?!");
    }
}

What do I have to do to make the ringbuffer-variable really global so every instance/call to the shared-library access one and the same instance of that variable?

From the comments it seems you want to allocate your memory in a process and use it in another.

For this purpose it might be a good idea to look at shared memory: 'man shmget' should be a good start.

Note that this is not specifically related to JNI and is a restriction from the OS.

EDIT: I would suggest you:

  1. read up on shared memory - you should understand the concepts of how this works.
  2. first try sharing memory between 2 simple applications
  3. only then implement in your JNI application

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