尝试将Haskell函数导出到C

时间:2019-05-12 23:06:36

标签: c haskell

我试图在Haskell中使用Foreign.C.Types从C调用Haskell,但它在编译器中始终显示此错误:

  * Unacceptable argument type in foreign declaration:
        `(CInt, CInt)' cannot be marshalled in a foreign call
    * When checking declaration:
        foreign export ccall "func_hs" func_hs :: (CInt, CInt) -> CInt
   |
15 | foreign export ccall func_hs :: (CInt, CInt) -> CInt
   | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

GHCi版本8.6.3编译的确切代码:

{-# LANGUAGE ForeignFunctionInterface #-}

module Func where

import Foreign.C.Types

verify_hp :: (CInt, CInt) -> CInt

verify_hp (hp, maxHp) = if hp < maxHp then hp + 10 else maxHp

func_hs :: (CInt, CInt) -> CInt

func_hs (hp, maxHp) = if verify_hp(hp,maxHp) == hp + 10 && hp < maxHp then hp + 10 else maxHp


foreign export ccall func_hs :: (CInt, CInt) -> CInt

为什么会发生这种情况,我该如何解决?

1 个答案:

答案 0 :(得分:5)

您不应该取消导出函数的参数。使用它代替您的func_hs,它将正常工作:

func_hs :: CInt -> CInt -> CInt

func_hs hp maxHp = if verify_hp(hp,maxHp) == hp + 10 && hp < maxHp then hp + 10 else maxHp


foreign export ccall func_hs :: CInt -> CInt -> CInt

在工作版本中,func_hs的C签名看起来像这样:

int func_hs(int hp, int maxHp);

在原始的非工作版本中,它必须看起来像这样:

int func_hs(tuple<int, int> hp_and_maxHp); // not valid C!