GHC / FFI: the haskell module is called, which imports the haskell libraries from C

Let's look at a general example of how a haskell function can be called from a C function:

Haskell module:

{-# LANGUAGE ForeignFunctionInterface #-} module Safe where import Foreign.C.Types fibonacci :: Int -> Int fibonacci n = fibs !! n where fibs = 0 : 1 : zipWith (+) fibs (tail fibs) fibonacci_hs :: CInt -> CInt fibonacci_hs = fromIntegral . fibonacci . fromIntegral foreign export ccall fibonacci_hs :: CInt -> CInt 

And module C:

 #include <HsFFI.h> #ifdef __GLASGOW_HASKELL__ #include "Safe_stub.h" extern void __stginit_Safe(void); #endif #include <stdio.h> int main(int argc, char *argv[]) { int i; hs_init(&argc, &argv); #ifdef __GLASGOW_HASKELL__ hs_add_root(__stginit_Safe); #endif i = fibonacci_hs(42); printf("Fibonacci: %d\n", i); hs_exit(); return 0; } 

I will compile and link it:

 $ ghc -c -O Safe.hs $ ghc test.c Safe.o Safe_stub.o -o test 

This is normal. But what if I need to import some library into the haskell module? For example, if I need to use bytestrings, I should add "import Data.Bytestring.Char8" (this module is taken as an example and is not used in the code):

 {-# LANGUAGE ForeignFunctionInterface #-} module Safe where import Foreign.C.Types import Data.Bytestring.Char8 fibonacci :: Int -> Int fibonacci n = fibs !! n where fibs = 0 : 1 : zipWith (+) fibs (tail fibs) fibonacci_hs :: CInt -> CInt fibonacci_hs = fromIntegral . fibonacci . fromIntegral foreign export ccall fibonacci_hs :: CInt -> CInt 

And this is not normal, at the moment I am getting an error:

 $ ...undefined reference to `__stginit_bytestringzm0zi9zi2zi0_DataziByteStringziChar8_' 

All I found in this problem is: an error in the GHC and the following changeet (a more formal description of the error)

As I use ghc-6.12.3, I already have this function. Therefore, I do not know how to fix this problem.

Perhaps it would be easier to create a shared library and dynamically link it to my C module?

+6
source share
1 answer

I do not think the error is related. Have you tried using --make ?

 $ ghc -c -O Safe.hs $ ghc --make test.c Safe.o Safe_stub.o -o test 

These errors are the errors you used to get 1 when binding pure-Haskell code to package dependencies without using --make ; GHC is in base by default, but if you want something from another package that doesn't work.

You can also try explicitly specifying packages if you want a more "manual" method:

 $ ghc -c -O Safe.hs $ ghc -package bytestring test.c Safe.o Safe_stub.o -o test 

1 Since GHC 7, --make by default.

+4
source

Source: https://habr.com/ru/post/905726/


All Articles