Export Haskell lib as DLL

自闭症网瘾萝莉.ら 提交于 2019-12-04 07:00:31

I was struggling with the same problem, but after a long fight, I managed to run the command from 64bit Excel. Follow these steps:

1) Create Adder.hs (notice ccall, not stdcall):

{-# LANGUAGE ForeignFunctionInterface #-}
module Adder where

adder :: Int -> Int -> IO Int  -- gratuitous use of IO
adder x y = return (x+y)

foreign export ccall adder :: Int -> Int -> IO Int

2) Create StartEnd.c:

#include <Rts.h>

void HsStart()
{
   int argc = 1;
   char* argv[] = {"ghcDll", NULL}; // argv must end with NULL

   // Initialize Haskell runtime
   char** args = argv;
   hs_init(&argc, &args);
}

void HsEnd()
{
   hs_exit();
}

3) Compile these files:

ghc -c Adder.hs
ghc -c StartEnd.c

4) Copy following files from "C:\Program Files\Haskell Platform\8.6.3\lib\include" to your build folder (remember to put stg/Types.h into stg folder). You may also copy all the contents of /include folder if you wish:

HsFFI.h
ghcconfig.h
ghcautoconf.h
ghcplatform.h
stg/Types.h

5) Create the dll:

ghc -shared -o Adder.dll Adder.o Adder_stub.h StartEnd.o

6) Now open the Excel and use this macro (use first HsStart before Adder). Remember to link to your own folder:

Private Declare PtrSafe Function Adder Lib "C:\Users\User\haskell\Adder.dll" Alias "adder" _
  (ByVal x As Long, ByVal y As Long) As Long

Private Declare PtrSafe Sub HsStart Lib "C:\Users\User\haskell\Adder.dll" ()
Private Declare PtrSafe Sub HsEnd Lib "C:\Users\User\haskell\Adder.dll" ()

Private Sub Document_Close()
HsEnd
End Sub

Private Sub Document_Open()
HsStart
End Sub

Public Sub Test()
MsgBox "12 + 5 = " & Adder(12, 5)
End Sub

7) Be amazed!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!