How to return a list or array from block C in Haskell inline-c?

How to get list or array from block C in Haskell inline-c ? In other words, how to build complex data in C and work with it in Haskell. Something like that:

foo :: IO [Int]
foo = do
 what? <- [C.block| <what?> {
    ints = calloc(10, sizeof(int));
    // ...
    return <what?>;
  } |]
  return <what?>

I could copy the pointer and size to some Haskell type, but I would like to work with the list in Haskell, print it, encode in JSON, etc.

+4
source share
1 answer

Return a pointer to an array from your C code and use peekArrayto translate it into a list.

import Foreign.Marshal.Array
import Language.C.Inline

foo :: Int -> IO [Int]
foo size = [exp| int* { calloc($(int size), sizeof(int)) }] >>= peekArray size

peekArray . size , , Storable ( Int).

unboxed Vector.

+3

Source: https://habr.com/ru/post/1665400/


All Articles