【发布时间】:2018-09-14 03:29:13
【问题描述】:
我很好奇让 C++ 和 Python 相互交流最灵活、最高效、最无缝的方法是什么。 竞争者似乎是 Pybind11、Boost.Python,两者都不是(只需编写函数和包装器,如下所示)。
using namespace boost::algorithm;
static PyObject* strtest(PyObject* self, PyObject* args)
{
std::string s = "Boost C++ Libraries";
to_upper(s);
PyObject * python_val = Py_BuildValue("s", s.c_str());
return python_val;
}
PyMODINIT_FUNC initmath_demo(void)
{
static PyMethodDef methods[] = {
"Test boost libraries" },
{ NULL, NULL, 0, NULL }
};
PyObject *m = Py_InitModule("math_demo", methods);
}
【问题讨论】:
-
你想从 c++ 调用 python 代码,从 python 调用 c++ 代码,还是两者兼而有之?
-
在这个阶段,只需从 Python 调用 c++。 Python调用c++,c++更高效地执行一些操作,然后将结果传回给python。
-
pybind11 和 boost 在创建绑定方面做得很好。但是,在引入诸如 boost 之类的大依赖时,您需要三思而后行。如果您只需要一个用于 python 绑定的库,请使用 pybind11,因为它更轻量级。我也对 cython 库有很好的体验。 pybind11 和 cython 的主要区别在于,使用 pybind11,您使用 c++ 编写绑定,而在 cython 中,您使用类似于 python 的语言编写绑定。