1

I'm using the JNI Invocation API in an attempt to wrap a Java library in C++.

My C++ classes are essentially containers for JNI jobjects with setter/getter methods to call JNI and retrieve data from said jobjects. What I am trying to figure out is how exactly I should go about trying to copy my class instances. For example, I want to do this:

absolute_date CURRENT_DATE = DATE;

My solution to this at the moment is to have a copy constructor which works like so:

  1. Make JNI calls to retrieve the member data of DATE.
  2. Make JNI calls to create a new jobject with the retrieved data.
  3. Set the jobject in CURRENT_DATE equal to the newly created jobject

This method is of course somewhat arduous, both programmatically and in terms of efficiency.

Copying over the jobject would be ideal however it means that if DATE goes out of scope then the absolute_date constructor will be called and in turn calling DeleteLocalRef (thus making the jobject for the newly created object invalid).

Is there a way to do what I want? I.e. is it possible to create unique clones of java objects within the JVM via JNI so that I can have 2 or more unique jobject references that each refer to unique java objects that have the same state (i.e. same member values etc)? I should mention that I cannot touch the Java source code. This all has to be done via calls to the invocation API.

If not, is there a way to do this using multiple jobject references i.e. if I have ten copies of DATE, each sharing the same jobject, is it somehow possible to get the destructor to ONLY call when the last remaining DATE Object gets destroyed? Smart pointers perhaps? If so how would I go about doing this as I am relatively new to this.

Thanks,

Ddor
  • 347
  • 1
  • 12
  • It is not clear to me what you want to do, copying or sharing. For your lifecycle issue you can use `NewLocalRef` to increase the ref count of your jobject and `DeleteLocalRef` to decrease it. This way you could share a jobject in a raii way. If you want your jobjects unique you need to create a new jobject e.g. with `clone` but then there is no issue in calling `DeleteLocalRef` in the destructor. And keep in mind that you cannot share local refs between threads. – mkaes Jan 03 '19 at 18:39

0 Answers0