Re: Call C function when Java object terminates/finalizes
William S Fulton <[email protected]> Sat, 30 Jan 2021 19:05:44 +0000
| Newsgroups | gmane.comp.programming.swig |
|---|---|
| Message-ID | <CANGqftB7chBEn4weeV4S5rJ44v7zaNRxCnQQ9ykKDWXJWPDcgA@mail.gmail.com> |
On Tue, 29 Dec 2020 at 09:41, lille stor <[email protected]> wrote: > Hi, > > I have a Java object (created from a Java class generated by SWIG) that > when it is about to terminate/finalize, I would like to call a C function > to release some resources from the C side of my program. Basically, I would > like to know how to extent the following Java method (generated by SWIG) > with a call to a C function to release resources (in bold): > > public synchronized void delete() { > if (swigCPtr != 0) { > if (swigCMemOwn) { > swigCMemOwn = false; > TestJNI.delete_Pool(swigCPtr); > * TestJNI.releaseResource(swigCPtr);* > } > swigCPtr = 0; > } > } > > Could you please tell how can this be achieved? > > You will need to wrap a C function to do whatever you want to do in C to release the resource. Below is a working example. The 'javadestruct' is needed to generate the modified delete() method. You may also need to provide a 'javadestruct_derived' typemap if Pool is a base class. The 'jtype' typemap is used to suppress the 'premature garbage collection prevention parameter' for the parameter in releaseResource. The 'jstype' typemap is used to marshal the Java Pool type as a long instead of a Pool type in the module class. The 'javain' typemap is used for the modified marshalling given the above typemaps. You can find the default versions of these typemaps in java.swg. %typemap(javadestruct, methodname="delete", methodmodifiers="public synchronized", parameters="") Pool { if (swigCPtr != 0) { if (swigCMemOwn) { swigCMemOwn = false; $jnicall; // The line below is added and makes this typemap different to the default one $module.releaseResource(swigCPtr); } swigCPtr = 0; } } %typemap(jtype, nopgcpp="1") Pool *resource_pointer "long" %typemap(jstype) Pool *resource_pointer "long" %typemap(javain) Pool *resource_pointer "$javainput" %inline %{ struct Pool { //... }; void releaseResource(Pool *resource_pointer) { // your code to use/release p } %} William _______________________________________________ Swig-user mailing list [email protected] https://lists.sourceforge.net/lists/listinfo/swig-user