将 C++ API 暴露给 Python

2021-12-24 00:00:00 python swig c++ boost

我目前正在处理一个项目,我必须用 Python 包装 C++ 类才能编写程序脚本.所以我的具体经验还涉及在我们的程序中嵌入 Python 解释器.

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 Python interpreter in our program.

我尝试的替代方案是:

  • Boost.Python

  • Boost.Python

我喜欢 Boost.Python 生成的更简洁的 API,但它需要用户安装额外的依赖项这一事实使我们转向了 SWIG.

I liked the cleaner API produced by Boost.Python, but the fact that it would have required that users install an additional dependency made us switch to SWIG.

SWIG

SWIG 对我们的主要优势是它不需要最终用户安装它来使用最终程序.

SWIG's main advantage for us was that it doesn't require end users to install it to use the final program.

您过去常常这样做,您对此有何经验?

What have you used to do this, and what has been your experience with it?

推荐答案

我都使用过(用于同一个项目):Boost 与 STL 更好地集成,尤其是 C++ 异常.此外,它的内存管理机制(试图桥接 C++ 内存管理和 Python GC)比 SWIG 更灵活.但是,SWIG 具有更好的文档,没有外部依赖项,如果您将库封装在 SWIG for Python 中,那么您就已经获得了 Java/Perl/Ruby 包装器的一半以上.

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.

我认为没有明确的选择:对于较小的项目,我会再次使用 Boost.Python,对于较大的长期项目,对 SWIG 的额外投资是值得的.

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.

相关文章