[Haskell-cafe] managing embedded structs

Henning Thielemann lemming at henning-thielemann.de
Sat Aug 27 10:23:13 UTC 2016


I want to write a Haskell interface to a C library that provides two data 
structures A and B, where B is contained in A. That is, if A is freed, 
then B is automatically freed, too.

There are two ways to obtain a Ptr B. Either construct it separately or as 
part of A, i.e.

   b0 :: Ptr B
   b0 <- createB

   b1 :: Ptr B
   b1 <- getBofA =<< createA

Now I want to let the garbage collector manage the resources for B in a 
ForeignPtr. The first case is easy:

   fb0 :: ForeignPtr B
   fb0 <- newForeignPtr deleteB =<< createB

But how to create an fb1?

   fa1 :: ForeignPtr A
   fa1 <- newForeignPtr deleteA =<< createA

   fb1 :: ForeignPtr B
   fb1 <- newForeignPtr ??? =<< withForeignPtr fa1 getBofA

Obviously, there is nothing I can insert for ???. fb1 must not have its 
own finalizer, because fa1 already has one. But I have to make sure that 
fa1 lives at least as long as fb1. How to do that?


More information about the Haskell-Cafe mailing list