Generate FFI call using Template Haskell

144 views Asked by At

In the Frames library, one has a readTable function, that generates a record type based on a CSV file.

Is it possible to generate a call like foreign import ccall unsafe "// c code" c_foo :: Int -> IO ()?

I've tried to accomplish so using a [d| ... |] and a [t| ... |] quasiquoters, but in both I get a parser error.

1

There are 1 answers

1
Alec On BEST ANSWER

Yes it is possible. The error message you are seeing is due to "// c code" being a "Malformed entity string". Anything more sane, and you are off to the races:

ghci> :set -XTemplateHaskell
ghci> ffi = [d| foreign import ccall unsafe "foo" c_foo :: Int -> IO () |]

Here is an example which does pretty much exactly what you are asking about. Note that both the packages inline-c and inline-java rely on this sort of thing.