考虑一个看起来像这样的Haskell数据类型
data MyData = MyData { arrInt :: [Int] , arrDouble :: [Double], arraySize :: N }
Run Code Online (Sandbox Code Playgroud)
这里N表示MyData记录的两个数组的大小.
是否可以将此(或MyData对象的某种Haskell"指针")传递给看起来像这样的C函数.
int myfunc (int* a, double* b, int N)
Run Code Online (Sandbox Code Playgroud)
我能够使用FFI来调用接受和返回简单数据类型的C函数,如Double,Int,Char等.但对于更复杂的类型,我不知道该怎么做.
你可以这样做:
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
Run Code Online (Sandbox Code Playgroud)