pybind11是一个轻量级的仅头文件库,它在 Python 中公开 C++ 类型,反之亦然,主要用于创建现有 C++ 代码的 Python 绑定。它的目标和语法类似于 David Abrahams 的优秀 Boost.Python 库:通过使用编译时自省来推断类型信息,从而最大限度地减少传统扩展模块中的样板代码。
安装:
brew install pybind11
参考官网的例子:example.cpp
#include <pybind11/pybind11.h>
int add(int i, int j)
{
return i + j;
}
PYBIND11_MODULE(example, m)
{
m.doc() = "pybind11 example plugin"; // optional module docstring
m.def("add", &add, "A function that adds two numbers");
}
ubuntu编译 :
pip3 install pybind11
在macos 编译时报错:
"__Py_FalseStruct", referenced from:
pybind11::detail::type_caster<bool, void>& pybind11::detail::load_type<bool, void>(pybind11::detail::type_caster<bool, void>&, pybind11::handle const&) in example-f398a2.o
"__Py_NoneStruct", referenced from:
pybind11::detail::type_caster<bool, void>& pybind11::detail::load_type<bool, void>(pybind11::detail::type_caster<bool, void>&, pybind11::handle const&) in example-f398a2.o
pybind11::cpp_function::initialize_generic(std::__1::unique_ptr<pybind11::detail::function_record, pybind11::cpp_function::InitializingFunctionRecordDeleter>&&, char const*, std::type_info const* const*, unsigned long) in example-f398a2.o
ld: symbol(s) not found for architecture x86_64
应该是 pybind11 需要链接python的库,在此添加参数:-undefined dynamic_lookup 解决该问题
c++ -O3 -Wall -shared -std=c++11 -undefined dynamic_lookup `python3 -m pybind11 --includes` example.cpp -o example`python3-config --extension-suffix`
在bash中测试一下:
python3
Type "help", "copyright", "credits" or "license" for more information.
>>> import example as e
>>> e.add(2,3)
5
>>> help(e) #查看描述信息
参考:
pybind11 :https://github.com/pybind/pybind11