Exposing a C++ API to Python

前端 未结 5 1319
夕颜
夕颜 2020-12-07 14:20

I\'m currently working on a project were I had to wrap the C++ classes with Python to be able to script the program. So my specific experience also involved embedding the Py

相关标签:
5条回答
  • 2020-12-07 14:32

    EDIT - the Robin project is sadly abandoned, and won't be much use today

    I've used Robin with great success.

    Great integration with C++ types, and creates a single .cpp file to compile and include in your shared object.

    0 讨论(0)
  • 2020-12-07 14:33

    pyrex or cython are also good and easy ways for mixing the two worlds.

    Wrapping C++ using these tools is a bit trickier then wrapping C but it can be done. Here is the wiki page about it.

    0 讨论(0)
  • 2020-12-07 14:45

    I've used both (for the same project): Boost is better integrated with the STL, and especially C++ exceptions. Also, its memory management mechanism (which tries to bridge C++ memory management and Python GC) is way more flexible than SWIG's. However, SWIG has much better documentation, no external dependencies, and if you get the library wrapped in SWIG for Python you're more than half-way there to getting a Java/Perl/Ruby wrapper as well.

    I don't think there's a clear-cut choice: for smaller projects, I'd go with Boost.Python again, for larger long-lived projects, the extra investment in SWIG is worth it.

    0 讨论(0)
  • 2020-12-07 14:46

    A big plus for Boost::Python is that it allows for tab completion in the ipython shell: You import a C++ class, exposed by Boost directly, or you subclass it, and from then on, it really behaves like a pure Python class.

    The downside: It takes so long to install and use Boost that all the Tab-completion time-saving won't ever amortize ;-(

    So I prefer Swig: No bells and whistles, but works reliably after a short introductory example.

    0 讨论(0)
  • 2020-12-07 14:50

    I suggest SIP. SIP is better than SWIG due to the following reasons:

    1. For a given set of files, swig generates more duplicate (overhead) code than SIP. SIP manages to generate less duplicate (overhead) code by using a library file which can be statically or dynamically linked. In other words SIP has better scalability.

    2. Execution time of SIP is much less than that of SWIG. Refer Python Wrapper Tools: A Performance Study. Unfortunately link appears broken. I have a personal copy which can be shared on request.

    0 讨论(0)
提交回复
热议问题