top | item 36782988

(no title)

bippingchip | 2 years ago

This is a somewhat tangential question to the new release, but there might be folks here that can answer this question.

Having used swig to create Python bindings for C++ code over 10 years ago, what’s the recommended way to do this in 2023? There’s still swig, there’s Cython, pybind11 and a few others. I do know swig and how complicated it can get with footguns abound when things grow more complex.

Is Cython the way to go? How does it hold up to the alternatives? Google search gives many articles on the topic, but many typical SEO optimized low-value, and those that do show a bit of depth, focus on the basic mechanics, not really on things hold up for larger projects…

discuss

order

gjulianm|2 years ago

I haven't used Cython too much, it does look really interesting but the translation layer worries me a little bit for more complex modules. However, I've been using pybind11 extensively and it's a delight. Well designed, documented, predictable, removes a massive amount of boilerplate, integrates perfectly well with C++ idioms (e.g., smart pointers), and doesn't completely lock you in, as you can still call the C API in a regular way.

bippingchip|2 years ago

Thank you! - I’ll give pybind11 a go.

gyrovagueGeist|2 years ago

Cython is the most general tool. It can be used to do anything from making bindings from C/Cpp to Python, Python to C/Cpp, to writing compiled “Python-like” code in an intermediate layer that can be used for managing your wrappers or just writing performant code.

If you just want the ability to provide a Python interface to a C/Cpp library PyBind11 will get you there in fewer LoC than Cython. Nanobind is an even lighter weight option.

I’ve heard Swig is a pain to use.

bippingchip|2 years ago

Thank you! Swig indeed can be a pain but having used it before I have become somewhat blind to it. But eg smart pointers are not easy to deal with well, I’ve found out recently… I’ll have a look at pybind11. I’ve worked on Cython codebases too, which indeed allows to really nicely compile Python code and interact with c code. It does get weird when using eg pyqt and native qt…

dagw|2 years ago

If all you need/want is to call c++ code from python then pybind11 is the way to go. Cython really comes into its own when you have some existing python code you want to 'port' to a C extension.

bippingchip|2 years ago

Thank you! For now I am just binding c++ to Python but I expect/fear the lines might start blurring, so cython might come in handy then.

plonk|2 years ago

The problem with SWIG bindings I’ve used is that they don’t have any type hints. They also don’t offer context managers to handle resources, so it’s a pain to use safely in Python.

From the user POV, the best bindings I’ve seen were wrappers with a Python API that calls C++ using Cython.