David Guo David Guo - 4 days ago 4
C++ Question

keep some sort of c++ object alive over multiple jni calls

My java code will call the exist c++ code to parse the file. it will generate an object which keep many data.
I will call the jni's second method to access such data,
When I call the second method, I have to parse the file again. it is obviously the right behavior.

Is there a way to handle this ?
BTW: I am newly to c++.


I am not sure if I understand your question correct. But I guess what you want to do is to keep some sort of c++ object alive over multiple jni calls.

You can do multiple things. First parse your file and store your c++ object in a global variable. This is the simplest solution but not a nice one.

You can also move the life cycle of your c++ object into java.

jlong java_some_class_jni_method(...)
    .... parse your text file ....
    MyParseclass* cls = new MyParseclass(...);
    return (jlong) cls;

But keep in mind that you need to delete this native c++ class again. So you need a jni method to this and be sure to call it.

void java_some_calls_jni_method(..., jlong clsPtr)
    MyParseclass* cls = (MyParseclass*)clsPtr;
    ... do maybe do something with cls and access the data...
    delete cls; // do not use the jlong again in any call

BTW: It would be much more helpful if you would post some code. But I hope this pseudo code here helps a little.