c++ - haskell FFI : Interfacing with simple C++?

标签 c++ haskell ffi

就我目前所读的内容而言,将 FFI 与 C++ 结合使用非常难以实现。最大的原因之一似乎是将 C++ 对象转换为 Haskell。我现在的问题是我没有任何 C 经验,但有几年 C++ 经验,而且我更喜欢 OOP。因此,自然而然地想从C++中受益。

那么我可以编写专供 Haskell FFI 使用的 C++ 程序来解决这些问题吗? C++ 可以在幕后做任何事情,但 API 会像 C 一样,即我不交换对象,没有重载的顶级函数等等。有什么需要注意的陷阱吗?

(将我的项目与您可能熟悉的项目进行比较:考虑使用 SciPy 的 Weave 来加速 Python 代码。)

最佳答案

是的,如果您在 C++ 代码之上公开 C API,则可以通过 FFI 使用 C++ 代码。

一个常见的模式是简单地将一个类的所有“方法”包装为 C 过程,这样该类的对象就可以被视为可以应用这些函数的不透明指针。

例如,给定代码(foo.h):

class foo
{
public:
  foo(int a) : _a(a) {}
  ~foo() { _a = 0; } // Not really necessary, just an example

  int get_a() { return _a; }
  void set_a(int a) { _a = a; }

private:
  int _a;
}

...您可以轻松创建所有这些方法的 C 版本 (foo_c.h):

#ifdef __cplusplus
typedef foo *foo_ptr;
extern "C"
{
#else
typedef void *foo_ptr;
#endif

foo_ptr foo_ctor(int a);
void foo_dtor(foo_ptr self);

int foo_get_a(foo_ptr self);
void foo_set_a(foo_ptr self, int a);
#ifdef __cplusplus
} /* extern "C" */
#endif

那么,必然有一些通过C++接口(interface)实现C接口(interface)的适配器代码(foo_c.cpp):

#include "foo.h"
#include "foo_c.h"

foo_ptr foo_ctor(int a) { return new foo(a); }
void foo_dtor(foo_ptr self) { delete self; }

int foo_get_a(foo_ptr self) { return self->get_a(); }
void foo_set_a(foo_ptr self, int a) { self->set_a(a); }

header foo_c.h 现在可以包含在 Haskell FFI 定义中。

关于c++ - haskell FFI : Interfacing with simple C++?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12475726/

相关文章:

c++ - boost.asio 套接字接收/发送功能不好吗?

c++ - C/C++ 中的日常文件维护工作

haskell - fmap 的自由定理

haskell - 理解类型错误 : "expected signature Int*Int->Int but got Int*Int->Int"

lua - 让Lua调用宿主程序?

haskell - 访问 C2HS 编码功能的现代方法是什么?

ruby - 安装 ffi ruby​​ gem 时找不到 ffi.h

c++ - 无法将此指针从 const Class<T> 转换为 Class<T>&

haskell - 使用类型类在 Haskell 应用程序中实现依赖倒置?

android - Android 上的 C++11 std::chrono::steady_clock 问题