我想从 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
这是一个非常简单的程序。我输入了下一个命令:
>ghc -c -O grep.hs
>ghc -shared -o grep.dll grep.o
Creating library file: grep.dll.a
之后,我有几个文件: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;
}
编译后,这段代码运行良好。
如果我使用 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
并运行 Cabal 构建系统:
>cabal configure --enable-shared
>cabal build
...
Creating library file: dist\build\libHSgrep-1.0-ghc7.6.3.dll.a
我得到了另一个 dll(尺寸很小),但我无法在 MS VS 中使用这个 dll,因为我收到很多链接器错误(如果我从 Haskell 平台获取 dll.a 文件)。
主要问题:
- 使用 Cabal 和 ghc 构建库有什么区别?
- 如何使用 Cabal 构建与使用 GHC 一样的 dll?
最佳答案
您可以通过将 ghc-options 添加到库设置来在 cabal 文件中设置其他选项。不确定您的情况需要什么,但我遇到了同样的问题(小库,链接器错误),对我来说以下设置解决了它:
ghc-选项:-staticlib
但我在 Xcode 的 iOS 项目中使用它。
关于haskell - 使用 Cabal 和 GHC 构建库的差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23543936/