Yes, you can use C ++ code through FFI if you open the C API on top of this C ++ code.
A common template is simply transferring all the "methods" of the class as C procedures, so that objects of this class can be considered as opaque pointers to which these functions can be applied.
For example, given the code ( foo.h ):
class foo { public: foo(int a) : _a(a) {} ~foo() { _a = 0; }
... you can easily create C versions of all these methods ( 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
Then there should be some adapter code that implements the C interface through the 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); }
The header foo_c.h can now be included in the FFI Haskell definition.
source share