5

How can I get a list or array from C block in Haskell's inline-c? In other words, how to construct complex data in C and work with it in Haskell. Something like this:

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

I could wrap a pointer and a size in some Haskell type, but I'd like to work with the list in Haskell, print it, encode in JSON, etc.

4

1 回答 1

4

从 C 代码返回指向数组的指针,并用于peekArray将其编组为列表。

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将元素从数组中拉出。StorableInt

您的数组变成未装箱的Vector.

于 2016-12-31T11:20:27.220 回答