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
This will produce two files, adder.o and adder_stub.o
compile up a DllMain() that starts up the Haskell
RTS-––a possible implementation is:
#include <windows.h>
#include <Rts.h>
EXTFUN(__stginit_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, __stginit_Adder);
return TRUE;
}
return TRUE;
}
Here, Adder is the name of the root module in the module
tree (as mentioned above, there must be a single root module, and hence a
single module tree in the DLL).
Compile this up:
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
Since this Haskell DLL depends on a couple of the DLLs that come with GHC,
make sure that they are in scope/visible.
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.