[Haskell-cafe] Anonymous FFI calls

Donn Cave donn at avvanta.com
Wed Feb 11 17:41:39 UTC 2015


Quoth Sylvain Henry <hsyl20 at gmail.com>,
> 2015-02-11 16:18 GMT+01:00 Francesco Mazzoli <f at mazzo.li>:
>
>> Relatedly, if I have some function pointer known at runtime that
>> addresses a C function that takes some arguments, I have no way to
>> invoke it from Haskell, since all FFI imports must be declared at
>> compile-time, and I don't know the address of the symbol I want to
>> execute at compile time.
>
> You can use FunPtr and wrapper imports to convert a FunPtr into a Haskell
> function.

For example,

  foreign import ccall "get_type1_fn" get_type1_fn
      :: IO (FunPtr (CInt -> IO CInt))
  foreign import ccall "dynamic" type1FunPtrToFun
      :: FunPtr (CInt -> IO CInt) -> (CInt -> IO CInt)

  main = do
      fp <- get_type1_fn
      let f = type1FunPtrToFun fp
      f 5 >>= print

I guess the key point in this demo is that a C function is able
to return a FunPtr.

	Donn


More information about the Haskell-Cafe mailing list