Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing std::unique_ptr to JNI

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?

like image 602
williamstome Avatar asked Oct 22 '22 16:10

williamstome


1 Answers

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).

like image 131
Praetorian Avatar answered Oct 31 '22 15:10

Praetorian