Haskell FFI: Interacting with Simple C ++?

From what I have read so far, using FFI with C ++ is very difficult. One of the main reasons, apparently, is the conversion of C ++ objects to Haskell. My problem is that I have no experience with C, but several years with C ++, and I also prefer OOP. Therefore, of course, I would like to use C ++.

So, can I write C ++ programs designed to use FFI Haskell to get around these problems? C ++ can do something under the hood, but the API will be C-like, that is, I do not exchange objects, do not overload top-level functions, and so on. Are there any pitfalls to look for?

(To compare my project with something you might be familiar with: consider using SciPy Weave to speed up Python code.)

+6
source share
1 answer

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; } // Not really necessary, just an example int get_a() { return _a; } void set_a(int a) { _a = a; } private: int _a; } 

... 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 } /* extern "C" */ #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.

+13
source

Source: https://habr.com/ru/post/925653/


All Articles