在之前的文章中提到了混合编程这个做法,也提到了c++中怎样去调用python脚本,然而,python毕竟是脚本,性能还是有限的,在一些对性能要求高的情景下面,还是需要使用c/c++来完成。那怎样做呢?众所周知,python的解析器是c写成的,而c++之所以能够调用python脚本,也是得益于这点,或者说,得益于cpython。正如上一文的例子一样,要像从c++中调用python是需要做很多的封装才能得到一个比较好用的接口,同理,如果直接使用cpython,其下场应该也是一样的,这里奉上一篇写得不错的cpython使用文章。作为以懒出名的程序员,自然不会满足于此,因此有一些好用的开源库就诞生了。
Boost.Python
boost.python库在安装好之后使用起来还是很简单的,只要在链接时增加对libboost_python.so的引用就可以了。但是boost.python的问题就在这里了,首先一点,这个库依赖于boost,为了使用这个功能而引入boost,代码有点略高了;其次,boost.python使用faber来做构建,其实faber用起来还是很简单的,但是问题在于faber的文档确实是有点不那么友好了,编译好之后的库放在哪里,怎样安装都没有找到,于是,我放弃了。不过还好,在黑暗中我找到了新的救星,那就是pybind11.
pybind11
我们直接来一段pybind11官方的说明吧,网址在这里
pybind11 is a lightweight header-only library that exposes C++ types in Python and vice versa,
mainly to create Python bindings of existing C++ code.
Its goals and syntax are similar to the excellent Boost.Python library by David Abrahams:
to minimize boilerplate code in traditional extension modules b