The Crystal Programming Language Forum

Binding with C++ code or Library

I found many excellent examples on binding Crystal with C code. However I could not find a single example on how to do the same with C++; i.e. binding to Classes/Objects …etc from C++ code-base or library.

Having some C++ library code exposing a number of classes I wanted to see the direct approach of binding with crystal.

I’m aware of bindgen being an attempt to “parse” the c++ code and produce generated wrapper code in crystal; but I would like to stay away from that type of boiler plate code and have a simple hand-written binding in the same way we do it with C.

Did you have any luck with that?

C++

simple

Yes… good luck

What you might not realize is that C++ has no facilities to be “bound” to a different language, there’s no stable binary interface to speak of. All there is is making sure to always use the same C++ compiler to conform to the same de-facto (i.e. not explicitly guaranteed) interface for library boundaries, or use another compiler that happens to do that (I think Clang attempts to match GCC at least on Linux). So any such project indeed needs to rely on a C++ compiler to mangle function names in the same way it mangled the original library. The easiest way to make use of that is by producing a wrapper that uses C++ and exposes a C interface.

That’s all in addition to considering the feature set of C++'s classes as anything remotely simple; making a mini-language to define all its possibilities would be a huge undertaking, and probably shouldn’t be in the scope of Crystal.
Neither would be re-implementing and maintaining large parts of the logic of most typical C++ compilers.

Anyway, if you care to look at another example of a project that auto-generates C++ → C → Crystal bindings, that’d be https://github.com/oprypin/crsfml/tree/master/src/graphics

2 Likes

Many thanks for the detailed response; it was both insightful and helpful.

I wasn’t aware of those challenges. It sounds funny to me that CRSFML had to wrap the the C++ code with C so it can bind to Crystal. I was hoping to find an easier solution.