是的,您可以通过FFI使用C++代码,只要在该C++代码上方公开C API即可。
一种常见的模式是将类的所有"方法"简单地包装为C程序,以便将该类的对象视为不透明指针,这些函数可以应用于该指针。
例如,给定代码(foo.h
):
class foo
{
public:
foo(int a) : _a(a) {}
~foo() { _a = 0; }
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
}
#endif
那么,必须有一些适配器代码通过C++接口实现C接口 (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); }
现在可以在Haskell FFI定义中包含头文件foo_c.h
。