Add Java support for std::unique<T> for input parameters.
This works by transferring ownership of the underlying C++ memory from the target language proxy class to an instance of the unique_ptr which is passed to the wrapped function via std::move. The proxy class has a new swigRelease() method which sets the underlying C++ pointer for the proxy class to null, so working in much the same way as std::unique_ptr::release(). Any attempt at using the proxy class will be the same as if the delete() function has been called on the proxy class. That is, using a C++ null pointer, when a non-null pointer is usually expected. This commit relies on the previous commit that uses std::move on the temporary variable used for the wrapped function's input parameter as std::unique_ptr is not copyable, it has move-only semantics.
This commit is contained in:
parent
64fa88c0eb
commit
6b361bf050
5 changed files with 94 additions and 1 deletions
|
|
@ -8,19 +8,42 @@
|
|||
* ----------------------------------------------------------------------------- */
|
||||
|
||||
%define %unique_ptr(TYPE)
|
||||
|
||||
%typemap (jni) std::unique_ptr< TYPE > "jlong"
|
||||
%typemap (jtype) std::unique_ptr< TYPE > "long"
|
||||
%typemap (jstype) std::unique_ptr< TYPE > "$typemap(jstype, TYPE)"
|
||||
|
||||
%typemap(in) std::unique_ptr< TYPE > (TYPE *unique_temp)
|
||||
%{ unique_temp = *(TYPE **)&$input;
|
||||
$1.reset(unique_temp); %}
|
||||
|
||||
%typemap(javain) std::unique_ptr< TYPE > "$typemap(jstype, TYPE).swigRelease($javainput)"
|
||||
|
||||
%typemap (out) std::unique_ptr< TYPE > %{
|
||||
jlong lpp = 0;
|
||||
*(TYPE **) &lpp = $1.release();
|
||||
$result = lpp;
|
||||
%}
|
||||
|
||||
%typemap(javaout) std::unique_ptr< TYPE > {
|
||||
long cPtr = $jnicall;
|
||||
return (cPtr == 0) ? null : new $typemap(jstype, TYPE)(cPtr, true);
|
||||
}
|
||||
|
||||
%typemap(javarelease) TYPE %{
|
||||
protected static long swigRelease($javaclassname obj) {
|
||||
long ptr = 0;
|
||||
if (obj != null) {
|
||||
if (!obj.swigCMemOwn)
|
||||
throw new RuntimeException("Cannot release ownership as memory is not owned");
|
||||
ptr = obj.swigCPtr;
|
||||
obj.swigCMemOwn = false;
|
||||
obj.delete();
|
||||
}
|
||||
return ptr;
|
||||
}
|
||||
%}
|
||||
|
||||
%template() std::unique_ptr< TYPE >;
|
||||
%enddef
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue