[Haskell-cafe] Dynamically Linking Foreign Functions

Richard Warburton richard.warburton at gmail.com
Thu Dec 31 04:28:01 EST 2009

Apologies in advance for the length of this email, but I've tried to
be as clear as possible.  Any help on the matter most appreciated.

Goal: I have a simple interpreter for a language that I've written,
and I wish to implement an FFI.  My ideal api would be like 'ctypes'
in python.  Here's an example:

from ctypes import *
libc = CDLL("libc.so.6")
libc.printf("An int %d, a double %f\n", 1234, c_double(3.14))

Prints out:

An int 1234, a double 3.140000

Implementation:  I am currently trying to use the dynamic linker in
order to specify the library string, for example the following seems
to work:

import Foreign
import Foreign.C.Types
import Foreign.C.String
import Monad (liftM)
import System.Posix.DynamicLinker

type Fun = CString -> IO CInt
foreign import ccall unsafe "dynamic" c_printf :: FunPtr Fun -> Fun

printf :: String -> IO Int
printf str = do
    withDL "libc.so.6" [RTLD_NOW] $ \dl -> do
        printf_ptr <- dlsym dl "printf"
        let fun = c_printf printf_ptr
        liftM fromIntegral $ withCString str fun

main = printf "hello world"

Problem: I don't understand how I can generate the foreign import
statements at runtime.  I am currently considering generating strings
of such expressions, and using hs-plugins in order to compile them.
This seems like a complete hack though - I'm dynamically loading a
haskell library in order to dynamically load a foreign library.

Another option is to write a dynamic loader in C, and then call this
from haskell, but how would I type the loading function - obviously I
can give it a CString for the library, and another for the function in
question - but what would the return type be?


  Richard Warburton

More information about the Haskell-Cafe mailing list