[Haskell-cafe] an array of pointers in FFI?
scook0 at gmail.com
Fri Aug 1 04:25:06 EDT 2008
2008/8/1 Galchin, Vasili <vigalchin at gmail.com>:
> Thanks Bulat! So since we are "talking" ;^) .... is there a function already
> in Foreign that will allow me to ...
> [a] -> Ptr (Ptr ()) i.e. map a list of type "a" to an array of ptrs of type
I think this is going to be a two-part operation: first you'll need to
store those values somewhere, so that you can produce pointers to
them. Then, you create a (foreign) array and fill it with the pointers
you got from step one. Of course, you'll need to manage memory for the
two stages separately, ensuring that the pointers don't outlive the
things they point to, and that both memory regions are freed when no
For example, if you have a list (xs :: [Int]), you can probably
achieve the first step using (mapM new xs),* which should give you a
list (ps:: [Ptr Int]). Then, you can do (newArray ps), which will
allocate an array and store the pointers in it, giving you a pointer
of type (Ptr (Ptr Int)). Once you're done, use (free) to clean up the
array of pointers, and also each of the individual elements of (ps).
If you only need the pointer array in a particular scope, you should
be able to make your life a bit easier using the (alloca) or (with)
family of functions.
* This is probably a bit wasteful, since it makes a separate
allocation for each element, but it does make life easier.
Hope this helps.
More information about the Haskell-Cafe