an array of pointers in FFI?

Hello, Is a (Ptr (Ptr a)) a polymorphic representation of an array of pointers of type "a"? I want to pass an array of pointers to a C function. Kind regards, Vasili

Hello Vasili, Friday, August 1, 2008, 9:08:05 AM, you wrote:
Is a (Ptr (Ptr a)) a polymorphic representation of an array of pointers of type "a"? I want to pass an array of pointers to a C function.
use Ptr (Ptr ()) Ptr () in haskell is like void* in C, it's used to represent pointer to arbitrary type. you can use castPtr to cast pointers between different types -- Best regards, Bulat mailto:Bulat.Ziganshin@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
"a"?
Kind regards, Vasili
On Fri, Aug 1, 2008 at 12:53 AM, Bulat Ziganshin
Hello Vasili,
Friday, August 1, 2008, 9:08:05 AM, you wrote:
Is a (Ptr (Ptr a)) a polymorphic representation of an array of pointers of type "a"? I want to pass an array of pointers to a C
function.
use Ptr (Ptr ())
Ptr () in haskell is like void* in C, it's used to represent pointer to arbitrary type. you can use castPtr to cast pointers between different types
-- Best regards, Bulat mailto:Bulat.Ziganshin@gmail.com

2008/8/1 Galchin, Vasili
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 "a"?
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 longer needed. 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. Stuart
participants (3)
-
Bulat Ziganshin
-
Galchin, Vasili
-
Stuart Cook