如何使用Haskell和FFI与C枚举接口



假设charm.c有一个enum key和一个返回key类型值的函数get_key()

如何公开对应的Haskell Key记录和函数getKey :: IO Key ?

在不手动指定每个枚举值如何映射到Haskell值的情况下,我如何做到这一点?

对于@KevinReid,这里有一个如何使用c2hs完成此操作的示例。

给定文件charm.h中的enum key(我不知道enum中有什么,所以我只是填写了几个值)

typedef enum
  {
    PLAIN_KEY = 0,
    SPECIAL_KEY  = 1,
    NO_KEY = 2
  }
key;
key get_key();

你可以像这样使用c2hs的枚举钩子:

{#enum key as Key {underscoreToCase} deriving (Eq, Show)#}

要绑定到一个函数,可以使用callfuncall更简单,但不做任何封送处理。以下是两者的例子。ffi包装的get_key将返回一个CInt,因此您需要手动封送它(如果使用call)或指定封送器(如果使用fun)。c2hs不包括enum编组器,所以我在这里编写了自己的编组器:

module Interface  where -- file Interface.chs
{#enum key as Key {underscoreToCase} deriving (Eq, Show)#}
getKey = cIntToEnum `fmap` {#call get_key #}
{#fun get_key as getKey2 { } -> `Key' cIntToEnum #}
cIntToEnum :: Enum a => CInt -> a
cIntToEnum = toEnum . cIntConv

C2hs将从中生成以下Haskell(稍微清理):

data Key = PlainKey
         | SpecialKey
         | NoKey
         deriving (Eq,Show)
instance Enum Key where
  fromEnum PlainKey = 0
  fromEnum SpecialKey = 1
  fromEnum NoKey = 2
  toEnum 0 = PlainKey
  toEnum 1 = SpecialKey
  toEnum 2 = NoKey
  toEnum unmatched = error ("Key.toEnum: Cannot match " ++ show unmatched)
getKey = cIntToEnum `fmap` get_key
getKey2 :: IO (Key)
getKey2 =
  getKey2'_ >>= res ->
  let {res' = cIntToEnum res} in
  return (res')
cIntToEnum :: Enum a => CInt -> a
cIntToEnum = toEnum . cIntConv
foreign import ccall safe "foo.chs.h get_key"
  get_key :: (IO CInt)
foreign import ccall safe "foo.chs.h get_key"
  getKey2'_ :: (IO CInt)

最新更新