首页 文章

通过FFI在C和Haskell之间传递类似结构的数据

提问于
浏览
5

考虑一个看起来像这样的Haskell数据类型

data MyData = MyData { arrInt :: [Int] , arrDouble :: [Double], arraySize :: N }

这里N表示MyData记录的两个数组的大小 .

是否可以将此(或MyData对象的某种Haskell“指针”)传递给看起来像这样的C函数 .

int myfunc (int* a, double* b, int N)

我能够使用FFI来调用接受和返回简单数据类型的C函数,如Double,Int,Char等 . 但对于更复杂的类型,我不知道该怎么做 .

1 回答

  • 5

    你可以这样做:

    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
    

相关问题