在Haskell中捕获C ++ FFI异常失败

时间:2014-08-22 07:14:54

标签: c++ haskell cabal

在Haskell中使用FFI到C ++时,我能够在cabal repl中运行函数时正确捕获异常,但在使用cabal run运行时,异常不会被捕获。

展示问题的简单cabal项目如下:

exception.cabal

name:                exception
version:             0.1.0.0
build-type:          Simple
cabal-version:       >=1.10
executable exception
  main-is:             Main.hs
  c-sources: main.cxx
  build-depends:       base >=4.7 && <4.8
  default-language:    Haskell2010
  extra-libraries:     stdc++

main.cxx:

# include <exception>
# include <stdexcept>

extern "C" int hs_exception() try
{
  throw std::logic_error("THIS FAILS!");
} catch(...) {
}

Main.hs

{-# LANGUAGE ForeignFunctionInterface #-}
module Main where

import Foreign.C.Types (CInt(..))


main = print c_hs_exception

foreign import ccall unsafe "hs_exception"
    c_hs_exception :: CInt

使用 REPL(即GHCI)

cabal repl
*Main> main
0

但是当使用 GHC编译并运行时失败:

cabal run
libc++abi.dylib: terminating with uncaught exception of type std::logic_error: THIS FAILS!
[1]    12781 abort      cabal run

我的编译器

➜ gcc --version
Configured with: --prefix=/Applications/Xcode.app/Contents/Developer/usr --with-gxx-include-dir=/usr/include/c++/4.2.1
Apple LLVM version 5.1 (clang-503.0.40) (based on LLVM 3.4svn)
Target: x86_64-apple-darwin13.3.0
Thread model: posix
➜ ghc --version
The Glorious Glasgow Haskell Compilation System, version 7.8.3

1 个答案:

答案 0 :(得分:1)

这是特定于Mac的,并报告为GHC bug 11829。修复是将标志-lto_library(LTO =链接时间优化)传递给Clang的链接器。这可以通过.cabal文件的可执行部分来完成,如下所示:

executable myprog
  ...
  if os(darwin)
    ld-options: -lto_library

如果直接调用-optl-lto_library,则为ghc

请注意,这会错误地建议您改为编写extra-libraries: to_library,这将无效。