FFI ExternalStructure - proper memory cleanup

Bert Freudenberg bert at freudenbergs.de
Sat Jan 20 23:23:46 UTC 2007


Am Jan 20, 2007 um 23:53  schrieb Jim McLoughlin:

> Hello,
>
> I have had a casual interest in squeak for a while, but just started
> doing more serious development in it recently (lots of fun!).  I am
> trying to bridge some functionality from the gnu scientific library
> (GSL) so I can do numerical stuff in squeak.
>
> I have successfully bridged the main functionality I need, but after
> some research am still a bit confused on the proper way to deal with
> memory allocated outside the VM:
>
> 1. I have ExternalStructure subclasses, e.g. GSLMatrix, that
> correspond to C structures in the GSL library.  (see
> http://www.gnu.org/software/gsl/manual/html_node/ 
> Matrices.html#Matrices
> for the structure definition.)
>
> 2. I allocate these structures using FFI with the GSL library, e.g.  
> via
>
> gsl_matrix * gsl_matrix_alloc (size_t n1, size_t n2)
>
> 3. I can deallocate the external memory with an FFI call:
>
> void gsl_matrix_free (gsl_matrix * m)
>
> My questions is WHEN/WHERE I should make this call to make sure
> external memory is cleaned up properly.  In the FFI examples and
> searching the website, I have seen this done in instance methods
> "free", "dispose", "destroy", as well as the "post-mortem"
> finalization described here: http://wiki.squeak.org/squeak/664.
>
> Can anyone describe or point me to the "best practice" I should use?

I think #destroy is the selector most commonly used for that. You  
should send it as soon as you're done using the object.

As a safety guard, you could use finalization in addition to that  
(sending #destroy). Or make it issue a warning so you know you forgot  
to properly release something.

> Similarly, I assume that if I created instances that point to external
> structures (e.g. created instances in my Workspace), and shutdown
> squeak, when I restart the VM, I have some instances with handles that
> point to invalid external addresses.  I am OK to just avoid using
> these objects, but will the fact that they still have these handles
> cause problems (e.g. when garbage collection occurs)?  If so, what is
> the best practice here - to reconstitute the external portion of the
> objects when the image is loaded?

On system startup, I'd nil out all those dangling references in all  
instances. And allocate them lazily when they are actually used.

- Bert -





More information about the Squeak-dev mailing list