在Haskell中使用FFI到C ++时,在中运行函数时,我能够正确捕获异常cabal repl
,但是在运行时cabal run
,不会捕获异常。
一个简单的显示问题的阴谋计划包括在下面:
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
这是Mac特定的,并报告为GHC错误11829。解决方法是将标志-lto_library
(LTO =链接时间优化)传递给Clang的链接器。可以使用.cabal文件的可执行部分来完成此操作,如下所示:
executable myprog
...
if os(darwin)
ld-options: -lto_library
或标志,-optl-lto_library
如果ghc
直接调用。
请注意,这将错误地建议您改写extra-libraries: to_library
,这将不起作用。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句