通过 FFI 在 C 和 Haskell 之间传递类似结构的数据
Passing struct-like data between C and Haskell via the FFI
考虑一个 Haskell 数据类型,它看起来像这样
data MyData = MyData { arrInt :: [Int] , arrDouble :: [Double], arraySize :: N }
这里N代表MyData记录的两个数组的大小。
是否可以将此(或 MyData 对象的某种 Haskell "pointer")传递给如下所示的 C 函数。
int myfunc (int* a, double* b, int N)
我能够使用 FFI 调用接受和返回简单数据类型(如 Double、Int、Char 等)的 C 函数。但对于更复杂的类型,我不知道该怎么做。
你可以这样做:
import Foreign
import Foreign.C
myfunc :: MyData -> IO CInt
myfunc d =
withArray (map fromIntegral $ arrInt d) $ \arr1 ->
withArray (map CDouble $ arrDouble d) $ \arr2 ->
c_myfunc arr1 arr2 (fromIntegral $ arraySize d)
foreign import ccall safe "myfunc"
c_myfunc :: Ptr CInt -> Ptr CDouble -> CInt -> IO CInt
考虑一个 Haskell 数据类型,它看起来像这样
data MyData = MyData { arrInt :: [Int] , arrDouble :: [Double], arraySize :: N }
这里N代表MyData记录的两个数组的大小。
是否可以将此(或 MyData 对象的某种 Haskell "pointer")传递给如下所示的 C 函数。
int myfunc (int* a, double* b, int N)
我能够使用 FFI 调用接受和返回简单数据类型(如 Double、Int、Char 等)的 C 函数。但对于更复杂的类型,我不知道该怎么做。
你可以这样做:
import Foreign
import Foreign.C
myfunc :: MyData -> IO CInt
myfunc d =
withArray (map fromIntegral $ arrInt d) $ \arr1 ->
withArray (map CDouble $ arrDouble d) $ \arr2 ->
c_myfunc arr1 arr2 (fromIntegral $ arraySize d)
foreign import ccall safe "myfunc"
c_myfunc :: Ptr CInt -> Ptr CDouble -> CInt -> IO CInt