7

我有一个返回的函数vector<MyClass>;将其更改为适合 FFI 的最佳方法是什么?

如果可能的话,我认为像这样的类型:: [CIntPointer]可能是一个不错的折衷方案。

4

1 回答 1

3

您可以定义自己的 C 函数来分配、释放、插入、删除等。这些函数可以包装您要访问的 C++ 容器。例如:

extern "C" {

Obj * obj_create()
{
  return new Obj();
}

void obj_destroy(Obj * schema)
{
  delete obj;
  obj = NULL;
}
...
...
}

然后在 FFI 中声明它们并以您喜欢的任何方式包装它们。

data SomeObject

type Obj = Ptr SomeObject

foreign import ccall unsafe "obj_create"
    createObj :: IO Obj

foreign import ccall unsafe "obj_destroy"
    destroyObj_ :: Obj -> IO ()

foreign import ccall unsafe "&obj_destroy"
    destroyObj :: FunPtr (Obj -> IO ())

一些陷阱:

  1. 确保使用 c++ 编译器(g++ 而不是 gcc)编译 C 文件。这将确保 stdc++ 库被正确拾取。
  2. 在 haskell 端编译程序/lib 时传递库位置 (-L) 和 libs(-lboost*) 以链接
于 2012-04-24T20:57:13.267 回答