I'm wrapping some C++ code with JNI, and stumbled upon the following factory function:
std::unique_ptr<MetricPlanner> create_metric_planner(*arguments*)
I need to pass a reference to the planner this function creates back to Java for later use, but am confounded as to a) how to pass it back, and b) what will happen to it once it gets passed on.
Normally, I've been passing like so:
Director *DIRECTOR = new Director(arguments);
return (jlong)DIRECTOR;
and it's worked like a charm.
Can someone explain the analogous process for referencing objects with JNI when a factory function returning this type of pointer is used, instead of a normal constructor?
Since you're passing the return value of the create_metric_planner
function to Java, and then using it later, you do not want the unique_ptr
to destroy the return value when its scope ends. To do that you must call unique_ptr::release
.
return (jlong)create_metric_planner( ... ).release();
Do not forget that at some point, when you're done using the object returned by that function, you must delete
it (or call some deleter function provided by the library you're using).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With