C2HS编组双指针

时间:2016-04-12 14:02:49

标签: haskell c2hs

当有如下功能时:

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表示错误)?

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

1 个答案:

答案 0 :(得分:1)

我想我已经弄明白了,我刚写了下面的marshallers:

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 #-}