无法将C函数导入Haskell

时间:2015-06-06 16:30:03

标签: c haskell ffi

我有一个调用Haskell函数的C程序。我希望Haskell函数负责确定数组(指针)的大小,所以我也希望Haskell从C语言指向malloc。我在Haskell中调用malloc_时出错。我不确定如何模仿malloc_在C malloc_((void *)&ints,sizeof(int),10);中调用Haskell的方式。

aux.c

void malloc_ (void **p, size_t size, int m) {
  *p = malloc(size*m);
}

的main.c

int *ints;
// want to call this function in Haskell, C doesn't know how large the array is
// malloc_((void *)&ints,sizeof(int),10);

int ints_size = setIntArray(ints);

for (int i = 0; i < ints_size; i++) {
  printf("ints[%d]: %d\n", i, ints[i]);
}

Arrays.hs

#include "aux.h"
-- this might be wrong
foreign import ccall "malloc_" malloc_ :: Ptr (Ptr ()) -> CSize -> CInt -> IO ()

foreign export ccall "setIntArray" setIntArray :: Ptr CInt -> IO CInt
setIntArray :: Ptr CInt -> IO (CInt)
setIntArray is =  do
  let r = 10 :: Int

  -- if I remove this and malloc in C then it is fine
  malloc_ (castPtr is) (fromIntegral $ sizeOf is) (fromIntegral r)


  x <- addArrayElement r 0

  return $ fromIntegral x

  where
    addArrayElement :: Int -> Int -> IO Int
    addArrayElement r pointerCounter =
      case pointerCounter >= r of
        True  -> return r
        False -> do
          let x = 1234
          poke (advancePtr is pointerCounter) (x :: CInt)
          addArrayElement r (pointerCounter + 1)

1 个答案:

答案 0 :(得分:1)

忽略了您的问题的其他问题,并且只是解决了有关致电malloc的问题:您有几个选择。

  • malloc已经以[{3}}为您导入,或者在这种情况下您甚至可以使用malloc

  • 如果你真的想自己导入malloc(也许你真的想要使用不同的分配器),只需从包装器中返回指针值,就可以让自己更方便,就像malloc本身一样:

    void *malloc_ (size_t size, int m) {
      return malloc(size*m);
    }
    

    然后foreign import ccall "malloc_" malloc_ :: CSize -> CInt -> IO (Ptr ()),然后调用它。

  • 如果你真的想使用这个out-argument-style void malloc_ (void **p, size_t size, int m),那么你必须为void *分配存储空间,这样你就可以将其地址作为第一个参数malloc_,就像你在C中所做的那样。

      my_allocated_pointer <- with nullPtr $ \pp -> do
        malloc_ pp (fromIntegral $ sizeOf (undefined :: CInt)) (fromIntegral 10)
        peek pp
    

    (现在开始变得有些愚蠢,因为mallocArray在内部使用malloc ......但它是你一般会使用的方法。)

    < / LI>