How to use a DLL in a Haskell project?

  1. You’ll need to use extra-lib-dirs and extra-libraries in the executable section of your .cabal file like so:

    name:                 MyApp
    version:              0.1.0.0
    synopsis:
    homepage:
    author:               simon.bourne
    category:
    build-type:           Simple
    cabal-version:        >=1.10
    
    library
      exposed-modules:      HelloWorld
      build-depends:        base >= 4.7 && < 5
      hs-source-dirs:       src
      default-language:     Haskell2010
    
    executable MyApp
      main-is:              Main.hs
      extra-lib-dirs:       lib
      extra-libraries:      helloWorld
      build-depends:        base >= 4.7 && < 5,
                            MyApp
      hs-source-dirs:       app
    
    default-language: Haskell2010
    

    Put your dll and .so in lib. Be warned, you’ll run into link order problems if you use a static library (.a instead of .so) on linux.

    See this for an example. Don’t be fooled by the name as it works fine with .so files.

  2. stack ghci should just work provided it can find your library (LD_LIBRARY_PATH on linux).

  3. The C API (mentioned in the comments on your question) is already there. You just need to write the Haskell FFI signatures, for example:

    foreign import ccall safe "helloWorld" c_helloWorld :: IO ()
    

    I’d very strongly advise using safe ccalls, and don’t wrap the functions in unsafePerformIO.

    If you need to pass non opaque structs, you might want to investigate c2hs or hsc2hs, but I don’t think you’ll need to. See this question for more details.

Leave a Comment