1

当有这样的功能时:

some_type_t* some_type_create(const char* name, char** errptr);

有没有办法让 C2HS 生成具有以下签名的 Haskell 绑定?

someTypeCreate :: String -> IO (SomeTypeFPtr, String)

到目前为止,这是我能得到的:

{#fun some_type_create as ^ 
    {`String', alloca- `Ptr CChar' peek*} -> `SomeTypeFPtr' #}

它以我得到的方式工作

someTypeCreate :: String -> IO (SomeTypeFPtr, (Ptr CChar))

但是我如何让它返回IO (SomeTypeFPtr, String)
(或者更好IO (Either String SomeTypeFPtr)),因为String代表错误)?

我假设我应该使用/编写一个不同的编组器来使用而不是peek转换结果类型,但我不太明白如何去做。

4

1 回答 1

1

我想我已经弄清楚了,我刚刚写了以下编组器:

nullableM :: (Ptr a -> IO b) -> Ptr a -> IO (Maybe b)
nullableM f ptr = if ptr == nullPtr
    then return Nothing
    else liftM Just $ f ptr
{-# INLINE nullableM #-}

toStringMaybe :: CString -> IO (Maybe String)
toStringMaybe = nullableM peekCString 
{-# INLINE toStringMaybe #-}

peekStringMaybe :: Ptr CString -> IO (Maybe String)
peekStringMaybe x = peek x >>= toStringMaybe
{-# INLINE peekStringMaybe #-}
于 2016-04-15T06:23:29.613 回答