JNI: reuse an object

K

Ken Kahl

Hello,

I am using JNI to use some functionality of a c++ program. From java I
call a native method, which creates some c++ objects. Is it possible to
reuse these objects, if I call the native method a second time? And how
does it work?

Thanks.

Ken
 
G

Gordon Beaton

I am using JNI to use some functionality of a c++ program. From java
I call a native method, which creates some c++ objects. Is it
possible to reuse these objects, if I call the native method a
second time? And how does it work?

JNI doesn't care or even know about any C++ objects you create. You
are free to reuse them as many times as you like, but you need to
manage them yourself.

How you keep track of them between calls from your Java application is
up to you, a static global table in your native code is one simple
way.

/gordon
 
T

Thomas Fritsch

Ken said:
Hello,

I am using JNI to use some functionality of a c++ program. From java I
call a native method, which creates some c++ objects. Is it possible to
reuse these objects, if I call the native method a second time? And how
does it work?
Of course. Just keep a static C++ pointer pointing to your newly created C++
object.

static MyCPlusPlusObject* pObj = NULL;

your_jni_function(...) {
if (pObj == NULL)
pObj = new MyCPlusPlusObject();
}

Or alternatively, you can store a C++ pointer into a Java member variable of
type int (by JNI-function SetIntField). And later you can get it back with
GetIntField.
 
K

Ken Kahl

Thomas said:
Of course. Just keep a static C++ pointer pointing to your newly created C++
object.

static MyCPlusPlusObject* pObj = NULL;

your_jni_function(...) {
if (pObj == NULL)
pObj = new MyCPlusPlusObject();
}

Thank you very much. It works in this way.

Ken
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,432
Messages
2,571,682
Members
48,796
Latest member
Greg L.

Latest Threads

Top