使用Cabal和GHC建立图书馆的差异

Sim*_*lex 7 dll haskell ffi ghc cabal

我想从Haskell代码构建库,并在我的C++项目中进一步使用这个库(共享库:dll左右).

我找到了简单的教程:http://blogging.makesmeanerd.com/?p = 367 并成功重复这个例子.

此外,我简化了这个例子,并获得下一个代码:

{-# LANGUAGE ForeignFunctionInterface #-}

module Grep where

import Foreign
import Foreign.C.String
import Data.Char

printCString :: CString -> IO ()
printCString s = do
    ss <- peekCString s
    putStrLn ss

getCStringFromKey :: IO CString
getCStringFromKey = do
    guess <- getLine
    newCString guess

foreign export ccall printCString :: CString -> IO ()
foreign export ccall getCStringFromKey :: IO CString
Run Code Online (Sandbox Code Playgroud)

这是一个非常简单的程序.我输入了下一个命令:

>ghc -c -O grep.hs
>ghc -shared -o grep.dll grep.o
Creating library file: grep.dll.a
Run Code Online (Sandbox Code Playgroud)

之后,我有几个文件:grep.dll,grep.dll.a和grep_stub.h(我的C++项目的头文件).我成功地在C++项目中使用了这个库.C++代码非常简单(我使用的是MS Visual Studio):

#include <iostream>
#include <string>
#include "grep_stub.h"

int main(int argc, char* argv[])
{
    std::string testStr;
    hs_init(&argc, &argv);
    HsPtr str1 = getCStringFromKey();
    std::cout << "We've get from Haskell: " << (char*)str1 << std::endl;

    HsPtr ss = "Hello from C++!";
    printCString(ss);

    std::cout << "Test application" << std::endl;
    std::cin.get();
    hs_exit();
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

编译后,此代码非常有效.

如果我使用Cabal构建系统构建相同的Haskell代码(grep.hs):

name:                grep
version: 1.0
synopsis:            example shared library for C use
build-type:          Simple
cabal-version:       >=1.10

library
  default-language:    Haskell2010
  exposed-modules:     Grep
  extra-libraries:     HSrts-ghc7.6.3
  extensions: ForeignFunctionInterface 
  build-depends:       base >= 4
Run Code Online (Sandbox Code Playgroud)

并运行Cabal构建系统:

>cabal configure --enable-shared
>cabal build
...
Creating library file: dist\build\libHSgrep-1.0-ghc7.6.3.dll.a
Run Code Online (Sandbox Code Playgroud)

我有另一个dll(小尺寸),但我不能在MS VS中使用这个dll,因为我得到了很多链接器错误(如果我从Haskell平台获得dll.a文件).

主要问题:

  • 使用Cabal和ghc构建库有什么区别?
  • 我如何使用GHC构建相同的dll,就像我使用GHC一样?

And*_*ras 1

您可以通过将 ghc-options 添加到库设置来在 cabal 文件中设置其他选项。不确定您的情况需要什么,但我遇到了同样的问题(小库,链接器错误),对我来说以下设置解决了它:

ghc-options: -staticlib

但我在 Xcode 的 iOS 项目中使用了它。