GHCi doesn't work with FFI export declarations/shared libraries

余生长醉 提交于 2019-12-01 04:35:41

You need to specify some more objects to link when invoking GHCi, because the C object c.o is particularly picky when it comes to linking order.

First, you need to add the bytestring package's object files. This is done by adding -package bytestring to the GHCi command line.

Then, you need to add the actual object file that defines callMeFromC. When FFISo.hs is compiled, it doesn't produce an object file that exports callMeFromC. It instead uses the GHC naming convention and exports Main_zdfcallMeFromCzuak4_closure, which actually is a static global variable pointing to the closure/"thunk" that contains the actual function definition and environment. This is so that you can't write something like this:

foregin export ccall foo :: IO ()
foo = undefined

...and have the runtime crash as soon as the program starts because the "function value" of foo can't be evaluated. The function definition is only inspected once the function is actually used.

GHC generates a stub file, which contains C code for calling the Haskell function from C. This file is called FFISo_stub.c, and is compiled into FFISo_stub.o for you. This object file exports the "C version" of callMeFromC that can be called directly. Feel free to inspect the generated code, it is quite interesting.

All in all, you need to use this command line when invoking GHCi:

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