用Cabal从C调用Haskell

Yan*_*n.F 13 c haskell cabal

我无法弄清楚如何构建一个使用外部函数接口调用Haskell的C SDL应用程序,我的主要是在C中,这是我的.cabal文件:

build-type:          Simple
extra-source-files:  README.md
cabal-version:       >=1.10

library
  exposed-modules:     AI     

  other-extensions:    ForeignFunctionInterface
  build-depends:       base >=4.9 && <4.10
  hs-source-dirs:      src/haskell
  default-language:    Haskell2010
  ghc-options:         -O2 -shared -fPIC -dynamic 
  extra-libraries:     HSrts-ghc8.0.2
Run Code Online (Sandbox Code Playgroud)

我按照此链接中的说明没有成功(它适用于OSX,而​​不是Linux).我正在通过以下方式成功构建Haskell源代码:

cabal install
Run Code Online (Sandbox Code Playgroud)

但我无法弄清楚如何以Haskell被识别并导入C的方式构建C代码.这是我的C和Haskell源代码的示例:

main.c中:

#include <stdio.h>
#include "game.h"
#include <SDL2/SDL.h>
#include <SDL2/SDL_timer.h>
#include <SDL2/SDL_image.h>
#include <SDL2/SDL_error.h>
#include "HsFFI.h" // include path not recognized
#include "AI_stub.h" // new! edited

int main( int argc, char** argv ) {
    hs_init(&argc, &argv);
    //HASKELL CALL
    int i;
    i = fibonacci_hs(42);
    printf("Fibonacci: %d\n", i);
    //END HASKELL CALL
    initializeSdl();
    window = createWindow(SDL_WINDOW_SHOWN | SDL_WINDOW_OPENGL);
    renderer = createRenderer();
    printf("Pre gameLoop\n"); 
    play();
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

AI.hs:

{-# OPTIONS_GHC -Wall                 #-}
{-# LANGUAGE ForeignFunctionInterface #-}

module AI 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
Run Code Online (Sandbox Code Playgroud)

PS:

  • 我正在开发ubuntu 18.04.
  • GHC版本是8.0.2.
  • Cabal版本是1.24.0.2.

小智 2

HsFFI.h位于您的 Haskell 安装文件夹中。我使用的是 Windows,它的位置是C:\Program Files\Haskell Platform\8.4.3\lib\include.

另外,当你构建 Haskell 模块时,.a应该生成一个文件。在我的机器上它被称为HSdll.dll.a. (我必须将其重命名为HSdll.a以满足 gcc 的要求,但我认为这应该是 Windows 特定的问题。)

然后以下命令将起作用:

gcc -I"C:\Program Files\Haskell Platform\8.4.3\lib\include" -L. -lHSdll main.c

注意:将 更改-I为您的 haskell 包含文件夹和文件-L.所在的位置.a