pybind11 tutorial

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

Python 调用 C++ 之 pybind11入门(macOS) | Ryan Li God

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值