Violet Giraffe
Violet Giraffe

Reputation: 33579

JNI: Is it safe to make java object a C++ class member?

My question coincides with this one, but there are no details there on my specific question. I can't understand one thing, I didn't find in the spec, and I'm quite surprised no one asked it. Consider the operator:

m_str = m_env->NewStringUTF("string");

How are references to Java objects created from C++ counted? May those objects be stored across native (C++) methods calls, or they will be collected once С++ method finishes execution and returns control to Java?

Upvotes: 2

Views: 492

Answers (1)

Gregory Pakosz
Gregory Pakosz

Reputation: 70204

It is as long as you use NewGlobalRef to convert the local reference to a global one before storing the Java object reference as a member of your C++ class.

After having converted the local reference to a global one, call DeleteLocalRef.

Finally, as part of your C++ destructor, make sure you call DeleteGlobalRef on the reference to the member Java object.

Your C++ class's copy constructor has to call NewGlobalRef too.

See Local and Global References.

Upvotes: 2

Related Questions