3 ms·
IME the best way to wrap C++ libraries for use in a C code base is to move at least one step higher then just wrapping every C++ class method with a C function
by flohofwoe 3y ago
IME the best way to wrap C++ libraries for use in a C code base is to move at least one step higher then just wrapping every C++ class method with a C function (because this will result in an absolutely miserable C experience - you're basically writing C++ code in C, but without all the C++ syntax sugar).
Instead write a higher level module in C++ on top of the C++ library which implements some of the "application logic" and only exposes a very small app-specific (and non-OOP) C API to the rest of the application.
For instance with Dear ImGui I often write the entire UI code in C++ and then only expose a minimal C API which connects the UI code to the rest of the application (which is written in C).
Same with managing C++ object lifetimes, let the C++ side take care of this as much as possible, and don't expose pointers to C++ objects to the C side at all.
- rezonant 3y agoI agree, with the caveat that given a heavy duty, large, and well-understood and -designed C++ API, the tradeoff of using a tool-generated wrapper might be worth it, even if such a wrapper may be more obtuse than one specifically considered by a human developer.
- flohofwoe 3y ago> well-understood and -designed C++ API Unfortunately these seem to be quite rare (Dear ImGui is such a well-designed C++ API, and I actually also use the code-generated cimgui bindings more frequently now in my projects (haven't tried the 'new' official bindings yet). Interestingly the Dear ImGui C++ API is much closer to a typical "flat" C API than a typical class-based C++ API (Dear ImGui is mostly just a flat soup of functions wrapped in a namespace and with some mild overloading).
- rezonant 3y agoVery true. Designing the C API with intention can be a way to fix the mistakes sometimes :-)