135 points · by tony · 9y ago · 117 comments
https://github.com/aldanor/ipybind
(still not on pypi but the plan is to release it soon)
Try cppyy [1]. It's very nice, though quite fresh. It's used extensively (as far as I can tell) at CERN, and derives from their cling C++ JIT interpreter. Plus it does lots of nice automatic transformations to make a C++ API more pythonic.
However, the very nice feature of cppyy is that it does much (most?) of what pybind11 does, but it can also be completely on-the-fly, in the sense that it relies on the cling JIT interpreter. This means that there is absolutely no need to maintain a compiled C++ part for your bindings, and so the problem of keeping the interface up to date is greatly mitigated: the equivalent changes to match the interface when using cppyy are _much_ smaller.
Often, one maintains a "C++ interface" layer in one's Python bindings (which could be created by pybind11, boost::python, or SWIG, for example), with a pure Python shim layer on top of that. cppyy allows you to do away with this two-layer structure entirely; all you need is the shim, if you need anything at all.
@aldanor recently gave a nice overview talk of what pybind11 can do: https://speakerdeck.com/aldanor/pybind11-seamless-operabilit...
Also, take a look at our documentation (http://pybind11.readthedocs.io) -- it contains detailed examples of many tricky use cases.
I've done both C++ and Python and never attempted to generate bindings, in the near future I may be faced with this though.
Does anyone have experience with using these and able to compare/contrast?
I'm afraid of C++, but if I can wrap it and learn how to use from a python REPL, I think I can handle... any recommendations/tuotirals/howtos would be much appreciated. (The library I want to wrap is https://github.com/openzim/libzim )
In my experience, the most difficult aspect of binding generation is not writing the glue code, but doing so in a scalable way. Manually writing bindings for any real-world C++ codebase would therefore be extremely tedious (IMHO), so having an automated system that does this work for you is a huge time saver.
Some larger libraries / frameworks have their own wrapping generators Btw, PyQt (which provides extremely good bindings to QT) for example has SIP which is worth looking at (it's open source).
Reading through some docs, it looks like pybind suits better for a python codebase that occasionally needs C++ pieces added in as you have to setup the C++ code to handle the py needs.
SWIG I was always impressed with exactly your point. You could sometimes just make 1 big header file in a facade pattern to expose some "start" buttons needed to run a huge c++ application and nothing else needed to be setup. No going back and forth.
Example usage here was a single heavy duty image processing application but using python has the distributor and work manager. C++ code was a "worker" and python and zeroMQ did everything else. So the only "connection" we needed was a start button and some metadata to the c++. Maybe 1 header file with 100-200 lines of code to make the bridge for SWIG.
(to anyone else reading) does that sound trivially simple to the do the same with pybind?
I point SWIG at the real headers in my projects and use ifdefs to block out things don't want SWIG to see. There are also a few rules that should be followed when doing this. Things like: don't let SWIG see overloads if the other language doesn't support them; don't return raw pointers that need to be deleted; don't let swig see std headers, etc...
Then I make SWIG (optionally) run as part of the build. Any warning it makes need to be resolved somehow because CI will reject commits causing warnings. It cost just a little more dev time, but prevents eons of debugging time.
Initially, all was great. But then we discovered a memory leak. He tried for weeks to identify it, but never could.
Cython would be my first choice.
I have used swig with Ruby, Lua and Java and it the code it makes doesn't leak unless the C/C++ code is bad, its just too simple.
A proprietary piece of software we use at work has a Python API for which they are using Boost.Python.
I've written a piece of software to get some data from the API and to analyze the retrieved data. The Python API has a bit of a "C++ smell" to it and doesn't feel completely pythonic but it's good enough. The bigger problem is that the vendor's idea of documentation is a single PDF generated from the class definitions and everything is either very sparesly or not at all commented, heh.
The project I was referring to :)
https://github.com/OSSIA/libossia/blob/master/OSSIA/ossia-py...
as you can see, it's just a matter of declaring the classes and methods you want to wrap. It was very straightforward and works extremely well.
Does anyone have experience taking one expensive method and replacing it with C/C++? Were the trade offs worth it?
Then, you try pypy. It may very well run your code 10 times faster with no work on your part.
If you can't or the result is not as good as expected, you can start using EXISTING compiled extensions. numpy, uvloop, ujson, etc.
After that, and only now, should you think about a rewrite. Numba for number related code, cython for classic hot paths or nuikta for the entire app: they can turn Python code into compiled code, and will prevent a rewrite in a low level tech.
If all of that failed, congratulation, you are part of the 0.00001%.
So rewriting bottlenecks in a compiled language is a good option. C or C++ will do. But remember you can do it in Rust too!
You may, late in the project, write partially some of your code in a DSL.
While with C++, you start from the beginning with a handicap for the whole project.
If you just want to reimplement some parts of your code in C for performance (I'd argue you neither need nor want C++, you shouldn't bother with C++'s object system and you should keep using Python)'s, CFFI might be simpler:
https://cffi.readthedocs.io/en/latest/overview.html#purely-f...
Because there's also overhead for transferring objects to/from pybind11 (it has to keep track of object lifetimes, figure out the conversions, etc), it's generally more beneficial to wrap big chunks of logic in C++ rather than every single method.
The productivity gains of Python scripts that could demux were huge. It made demuxing fast and easily accessible to all of the Python coders. Also, the underlying C++ code could be used in our C# environment too, although I'm not sure if they ever did that. So, we had the ability to use the exact same underlying C++ code in multiple dev environments to ensure consistency.
The downside, IMO, was maintaining the modules. The C++ code itself was short and easy to test (maybe 100 or 200 LOC), but you need good documentation and the ability to build the modules for various versions of Python, with various toolchains, on various systems, etc.
I would do it again if in the same or similar situation.
https://speakerdeck.com/aldanor/pybind11-seamless-operabilit...
(reimplementing rolling_stats from pandas that ends up being faster)
If you just need to bind simple number crunching functions, you may also write a small library exposing them with c linkage, then access them using ctypes.
For more advanced usage, you will probably benefit from using a binding framework instead of using the python c api.
int add(int i, int j) {
return i + j;
}Or std::vector<T>::operator[] invokes undefined behaviour if the argument is invalid (out of band).
Or printf() invokes undefined behaviour if an argument is of the wrong type (for example "%s" with a corresponding int).
Or strcpy invokes undefined behaviour if you give it invalid pointers (or non-null terminated strings, etc).
So, yeah, many functions can invoke undefined behaviour when they are called with bad arguments, that doesn’t make them bad functions.
The Python vs C++ joke here is that the minimal a + b example turns out to be unsafe to call with random numbers.
Take any language's FFI and bind to the C library atoi function. Poof, you have instant undefined behavior for bad string to int conversions.
If you want a safe, robust module that is based on FFI, you have to write some padding in the higher level language that avoids misusing the foreign API in any way.
Directly exposed FFI stuff is not safe and cannot reasonably be safe; it makes no sense to expect that.
I wonder if the "best" fix here, would be to use assembler intrinsics to maintain performance, possibly with a fallback to a type cast/promotion to a bigger int for the sum, and some form of defined behaviour for overflow on the python side? (reinventing the python number tower with full automatic promotion seems counter-productive here, as presumably the idea is to work with fast/simple/native (signed) integer math...)
Or just redefine the function to use unsigned ints.
add(INT64_MAX, 1)
Is undefined.If using Ada, similar kind of code would produce "raised CONSTRAINT_ERROR : program.adb:7 overflow check failed"
To be fair, Ada's behavior is easy to reproduce with a checked integer class like https://accu.org/index.php/journals/324
There millions of lines of code, from the best C/C++ programmers, even the kernel, that add two ints in all kinds of programs.
Why is this suddenly a valid concern, especially for a code example, not NASA's missile code or Tesla's self-driving libs?
(There isn't a way in C/C++ to request an exception or fault on integer overflow, which is what you'd want here, since you're running inside Python. A better conceptual fix is just doing the addition in Python, which is a more robust language than C/C++ for signed integer addition, but that kind of defeats the point of the example.)
This is incorrect.
See compiler options: -ftrapv, -fsanitize=undefined. See compiler builtins: __builtin_add_overflow and friends.