[Haskell-cafe] FFI C Structs
Aleš Bizjak
ales.bizjak0 at gmail.com
Fri Jul 18 14:29:22 EDT 2008
Hello,
Suppose I have a C struct like
typedef {
int a;
int *b;
} Foo;
typedef Foo *fooptr;
and all worker functions which are all basically int foofun (fooptr ,
fooptr, fooptr)
where the first one is a out argument and the other two are in arguments
and the return value
is (almost) irrelevant.
Now before I can pass arguments I have to initialize them and this is done
with void init(fooptr ) function and
all values have to be cleared which is done with void clear(fooptr ).
I tried to import this to haskell like this.
data Foo = Foo
type FFptr = ForeignPtr Foo
and because I would like to have a nice interface without manually
worrying about allocation and freeing up I
tried something like this:
foreign import ccall "&clear" clear :: FunPtr (Ptr Foo -> IO ())
foreign import ccall "init" init :: Ptr Foo -> IO ()
foreign import ccall "foofun" foofun_ :: Ptr Foo -> Ptr Foo -> Ptr Foo ->
IO Int
foofun :: FFptr -> FFptr -> FFptr
foofun f1 f2 = unsafePerformIO f
where f = withForeignPtr f1 (p1 ->
withForeignPtr f2 (p2 ->
do p3 <- malloc
init p3
r <- foofun_ p3 p1 p2
newForeignPtr clear p3
Now should that work or do I have to do some more reading on ffi and if
so, would anyone recommend some material
because this is all I could come up with.
PS: An example of a haskell binding like this would be even more useful,
if anyone knows of such.
More information about the Haskell-Cafe
mailing list