gpt4 book ai didi

Haskell FFI : How do you wrap C++ collections?

转载 作者:行者123 更新时间:2023-12-04 12:42:41 24 4
gpt4 key购买 nike

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

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

最佳答案

您可以定义自己的 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 ())

一些陷阱:
  • 确保使用 c++ 编译器(g++ 而不是 gcc)编译 C 文件。这将确保 stdc++ 库被正确拾取。
  • 在 haskell 端编译程序/lib 时传递库位置 (-L) 和 libs(-lboost*) 以链接
  • 关于Haskell FFI : How do you wrap C++ collections?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9458850/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com