Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using the Haskell FFI to marshal structs; also, how to use FunPtr

Tags:

haskell

ffi

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?
like image 760
develhevel Avatar asked Jan 19 '23 14:01

develhevel


1 Answers

Marshalling

To marshal structures, you will need to use a Storable class instance to marshal data back and forth, via peek and poke.

See this previous answer for an example: How to use hsc2hs to bind to constants, functions and data structures?


FunPtr

FunPtr is only needed when you want to pass a function across the FFI boundary as a first-class value, not for calling foreign functions. Precisely:

A value of type FunPtr a is a pointer to a function callable from foreign code. The type a will normally be a foreign type, a function type with zero or more arguments

An example, registering a call back function:

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

Since we have to pass p_free itself to a Haskell function, we have to let Haskell know this is actually a C function. The FunPtr wrapper controls that.

like image 123
Don Stewart Avatar answered Feb 01 '23 08:02

Don Stewart