Crashes on FFI calls to Visual Studio-built C library
I want to call third-party C library using ffi on Windows. Everything works fine with 32-bit GHC distribution, however 64-bit program crashes as soon the ffi call is being made. Interestingly, the same program works when run with runghc
. Just the compiled .exe crashes.
Consider the following C++ library code:
// adder.cpp
extern "C"
{
__declspec(dllexport) int _cdecl add(int a, int b)
{
return a + b;
}
}
and the following Haskell code using the library:
import Foreign.C
foreign import ccall unsafe "add" add :: CInt -> CInt -> IO CInt
main = (add 5 2) >>= print
It does work on 32-bit architecture and in ghci (on all architectures). Why does it not work as 64-bit executable?
Notes:
- it works if the library is built with MinGW. However, this is not an acceptable workaround for me, since the library I want to call is external and closed-source
- the problem seems to be related to the import library file handling — if I replace the MSVC-generated one with the MinGW-generated .lib import library, it works (even with MSVC-generated .dll)
Repro
I attach archive repro_src.7z
with source files (as presented here) and a build.bat
script building binaries. It needs to have both GCC/GHC and MSVC compilers in the path. (so it should be called from MSVC's x64 Native Tools Command Prompt
)
It creates two folder — in one it builds the library with MinGW, in the another one — with MSVC. The Haskell program crashes only with MSVC build of library. However, the Haskell source file works fine with runghc/ghci.
Run the build.bat
and ender the bin-msvc directory. The Caller.exe
program crashes. However, runghc -ladder ..\src\Caller.hs
gives the expected result.
If you don't have MSVC installed, I provide also a package with all the C++ sources built — repro_bin.7z
. I have used Microsoft Visual Studio 2013 and MinGHC 7.10.1, both 64-bit targeting. Same happens with GHC 7.8.4.
Please let me know, if you need any further information to investigate this report.