3

我正在尝试从using调用以下C函数。Haskellc2hs

void rd_kafka_conf_set_rebalance_cb (
    rd_kafka_conf_t *conf,
    void (*rebalance_cb) (rd_kafka_t *rk,
                          rd_kafka_resp_err_t err,
                          rd_kafka_topic_partition_list_t *partitions,
                          void *opaque));

我不熟悉c2hs并且在声明绑定时遇到了麻烦。

这是我尝试过的:

--callback type
type RebalanceCbFun = 
    Ptr RdKafkaT -> CInt -> Ptr RdKafkaTopicPartitionListT -> Ptr Word8 -> IO ()

foreign import ccall safe "wrapper" 
    mkRebalanceCallback :: RebalanceCbFun -> IO (FunPtr RebalanceCbFun)

foreign import ccall unsafe "rd_kafka.h &rd_kafka_conf_set_rebalance_cb"
    rdKafkaConfSetRebalanceCb :: Ptr RdKafkaConfT -> FunPtr RebalanceCbFun -> IO ()

但是,在编译此代码时出现以下错误:

Unacceptable type in foreign declaration:
  ‘Ptr RdKafkaConfT
   -> FunPtr
        (Ptr RdKafkaT
         -> Int32 -> Ptr RdKafkaTopicPartitionListT -> Ptr Word8 -> IO ())
   -> IO ()’ cannot be marshalled in a foreign call
  A foreign-imported address (via &foo) must have type (Ptr a) or (FunPtr a)
When checking declaration:
  foreign import ccall unsafe "static rd_kafka.h &rd_kafka_conf_set_rebalance_cb" rdKafkaConfSetRebalanceCb
    :: Ptr RdKafkaConfT -> FunPtr RebalanceCbFun -> IO ()

我不明白缺少什么部分PtrFunPtr这里。我还尝试将整个包装rdKafkaConfSetRebalanceCbFunPtr这样:

foreign import ccall unsafe "rd_kafka.h &rd_kafka_conf_set_rebalance_cb"
    rdKafkaConfSetRebalanceCb :: FunPtr (Ptr RdKafkaConfT -> FunPtr RebalanceCbFun -> IO ())

不确定它是否有意义,尽管它可以编译......但是我不知道如何使用这个函数,这就是我尝试过的(这是我最后想要的签名):

kafkaConfSetRebalanceCb :: RdKafkaConfTPtr -> RebalanceCbFun -> IO ()
kafkaConfSetRebalanceCb conf cb = do
    cb' <- mkRebalanceCallback cb
    withForeignPtr conf $ \c -> rdKafkaConfSetRebalanceCb c cb'
    return ()

现在它抱怨我没有要调用的函数,只有一个指向函数的指针(因为那个FunPtr包装)。

你能告诉我如何C正确地为C上面的签名完成绑定吗?

4

1 回答 1

4

以下文件对我来说编译得很好(带有ghc -c Test.hs)。唯一真正的区别是我&在外国进口中省略了。

{-# LANGUAGE ForeignFunctionInterface #-}
module Test where
import Data.Word
import Foreign.C.Types
import Foreign.Ptr
import Foreign.ForeignPtr

newtype RdKafkaT = RdKafkaT (Ptr RdKafkaT)
newtype RdKafkaConfT = RdKafkaConfT (Ptr RdKafkaConfT)
newtype RdKafkaTopicPartitionListT = RdKafkaTopicPartitionListT (Ptr RdKafkaTopicPartitionListT)

type RebalanceCbFun = 
    Ptr RdKafkaT -> CInt -> Ptr RdKafkaTopicPartitionListT -> Ptr Word8 -> IO ()

foreign import ccall safe "wrapper" 
    mkRebalanceCallback :: RebalanceCbFun -> IO (FunPtr RebalanceCbFun)

foreign import ccall unsafe "rd_kafka.h rd_kafka_conf_set_rebalance_cb"
    rdKafkaConfSetRebalanceCb :: Ptr RdKafkaConfT -> FunPtr RebalanceCbFun -> IO ()

kafkaConfSetRebalanceCb :: ForeignPtr RdKafkaConfT -> RebalanceCbFun -> IO ()
kafkaConfSetRebalanceCb conf cb = do
    cb' <- mkRebalanceCallback cb
    withForeignPtr conf $ \c -> rdKafkaConfSetRebalanceCb c cb'
于 2016-03-15T09:47:27.363 回答