Object cleanup and weak references

Bill Baxter wbaxter at gmail.com
Sat Oct 28 14:48:08 PDT 2006


Maybe this message from a few days ago helps?
http://www.digitalmars.com/d/archives/digitalmars/D/learn/5016.html
It may require wrapping your SDL_Surfaces in wrapper objects, becuase 
the above doesn't work with structs.

Something like:

class CSDL_Surface
{
   this(SDL_Surface *s) { surf = s; }
   ~this() { SDL_FreeSurface(surf); }
   SDL_Surface *surf;
}
Then you'll need to always use the class destructor to free surfaces too 
to maintain 1-1 correspondence between live surfaces and objects.

Thomas is probably the only one who can say if it'll work or not, though.

--bb

Max Bolingbroke wrote:
> Hi,
> 
> I was writing a thin wrapper for SDL in D, in which I hoped to do 
> something like the following (very much simplified from real code):
> 
> static this()
> { SDL_Init(INIT_EVERYTHING); }
> 
> static ~this()
> { SDL_Quit(); }
> 
> class Surface()
> {
>     SDL_Surface* handle;
> 
>     public this(char[] filename)
>     { handle = IMG_Load(filename); }
> 
>     ~this()
>     { SDL_FreeSurface(handle); }
> }
> 
> It looks great and I don't have to remember to explicitly free my 
> surfaces. However, there are two problems with Ds shutdown process that 
> mean this won't work:
> 
> 1) In my case the static constructor / destructors were located in a 
> separate "initialize" module, and it turned out that on quit it was 
> being destructed (running SDL_Quit) BEFORE the GC ran and destructed my 
> Surface objects (running SDL_FreeSurface). Clearly we can't Free after 
> we have Quit, so that's problem number 1.
> 
> 2) Even if I removed the call to SDL_Quit it would still fail with an 
> access violation on SDL_FreeSurface because D has somehow caused it to 
> go away at the point the destructor was run (Anyone know why? I'm using 
> Derelict for the SDL imports, by the way).
> 
> So, I searched the site and found this guy 
> (http://www.digitalmars.com/d/archives/digitalmars/D/learn/729.html) who 
> was trying to do >exactly< the same thing as me, and had exactly the 
> same problem. I have adopted his solution (an associative array of 
> references that is added to when a Surface is created and systematically 
> disposed in the static destructor before SDL_Quit occurs) and it works 
> nicely, but it means that we have the problem of memory bloat: no 
> Surface can ever be GCed before the program terminates because the array 
> of surfaces to kill off holds a reference to every single one!
> 
> The perfect solution to this is weak references, but I've done some more 
> searching and found some posts from a few years back saying that 
> apparently D does not support these wonderful things!
> 
> So, can anyone tell me if this is still true? And if it is, is there 
> another, cleaner, solution to my problem?
> 
> Thanks for any help, and sorry about the long post!
> 
> Max



More information about the Digitalmars-d-learn mailing list