If you want to package up Haskell code to be called from other languages, such as Visual Basic or C++, there are some extra things it is useful to know. The dirty details are in the Foreign Function Interface definition, but it can be tricky to work out how to combine this with DLL building, so here's an example:
Use foreign export declarations to export the Haskell functions you want to call from the outside. For example,
module Adder where adder :: Int -> Int -> IO Int -- gratuitous use of IO adder x y = return (x+y) foreign export stdcall adder :: Int -> Int -> IO Int |
Compile it up:
ghc -c adder.hs -fglasgow-exts |
compile up a DllMain() that starts up the Haskell RTS---a possible implementation is:
#include <windows.h> #include <Rts.h> EXTFUN(__init_Adder); static char* args[] = { "ghcDll", NULL }; /* N.B. argv arrays must end with NULL */ BOOL STDCALL DllMain ( HANDLE hModule , DWORD reason , void* reserved ) { if (reason == DLL_PROCESS_ATTACH) { /* By now, the RTS DLL should have been hoisted in, but we need to start it up. */ startupHaskell(1, args, __init_Adder); return TRUE; } return TRUE; } |
gcc -c dllMain.c |
Construct the DLL:
ghc --mk-dll -o adder.dll adder.o adder_stub.o dllMain.o |
Start using adder from VBA---here's how I would Declare it:
Private Declare Function adder Lib "adder.dll" Alias "adder@8" (ByVal x As Long, ByVal y As Long) As Long |
Building statically linked DLLs is the same as in the previous section: it suffices to add -static to the commands used to compile up the Haskell source and build the DLL.