0

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.

duplode
  • 33,731
  • 7
  • 79
  • 150
Nick Tchayka
  • 563
  • 3
  • 14
  • 5
    It is possible. `[d| foreign import ccall unsafe "malloc" c_malloc :: Int -> IO () |]`, for example, works. There are some examples of template Haskell with FFI [here](https://wiki.haskell.org/Foreign_Function_Interface#Inline_FFI_calls). Note also that this is exactly what [inline-c](https://hackage.haskell.org/package/inline-c) and [inline-java](https://hackage.haskell.org/package/inline-java) rely on. – Alec Apr 04 '17 at 08:41
  • @Alec could you make this an answer so I can accept it? :) – Nick Tchayka Apr 05 '17 at 08:40

1 Answers1

1

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.

Alec
  • 31,829
  • 7
  • 67
  • 114