4

I have some questions about the ffi in haskell.

first of all i'm trying to work with c structs in haskell.

there i have some questions: i have a struct like

struct foo{int a; float b;};
  1. when could i use data Foo = Foo { a :: Int, b :: Float } deriving (Show, Eq)
  2. when i have to implement a storable with peek and poke?

okay now a question about FunPtr

  • i dont know when to use FunPtr why a normal definition like Ptr CInt -> IO CInt is not enough?
4

1 回答 1

9

编组

要编组结构,您需要使用Storable类实例来来回编组数据,通过peekpoke

有关示例,请参见上一个答案:如何使用 hsc2hs 绑定到常量、函数和数据结构?


FunPtr

FunPtr仅当您想将函数作为一等值传递越过 FFI 边界时才需要,而不是用于调用外部函数。恰恰:

FunPtr a 类型的值是指向可从外部代码调用的函数的指针。类型 a 通常是外来类型,一个有零个或多个参数的函数类型

一个例子,注册一个回调函数:

foreign import ccall "stdlib.h &free"
   p_free :: FunPtr (Ptr a -> IO ())

由于我们必须将p_free自身传递给 Haskell 函数,我们必须让 Haskell 知道这实际上是一个 C 函数。FunPtr包装器控制它。

于 2011-06-05T15:48:10.427 回答