[Haskell-cafe] Seeking advice on best practices with FFI

PJ Durai pjdtech2000 at gmail.com
Fri May 9 17:45:29 EDT 2008


I am trying to write FFI wrappers for a dynamic library in windows.
I would like to get some help in how to go about doing things.

For example for this C function, the import and wrapper I came up with
are listed below.

-- STATUS LNPUBLIC NSFDbOpen (char far *PathName, DBHANDLE far *rethDB);

foreign import stdcall "nsfdb.h NSFDbOpen" nsfDbOpen' ::CString -> Ptr
CInt -> IO CInt

type DbHandle = CInt

nsfDbOpen :: String -> IO DbHandle
nsfDbOpen dbname = alloca $ \ptr -> do
                     db <- newCString dbname
                     rc <- nsfDbOpen' db ptr
                     handle <- peek ptr
                     if rc /= 0 then error "dbopen failed" else return handle

Q: Does that look ok?  Is the db <- newCString leaking ?

Q:  How would I import and call a function with signature like this

calling C code:

char str1[MAX_PATH];
char str2[MAX_PATH];

GetStringValues( str1, str2);

called C function signature is:
void  GetStringValues( char* s1, char* s2);

i.e. how would the haskell import (and the wrapper function) look like
in situation like this (where I have to pass preallocated char array
to C code and get it filled up)?

Appreciate your time.

More information about the Haskell-Cafe mailing list