栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

pybind11 tutorial

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

pybind11 tutorial

pybind11是一个轻量级的仅头文件库,它在 Python 中公开 C++ 类型,反之亦然,主要用于创建现有 C++ 代码的 Python 绑定。它的目标和语法类似于 David Abrahams 的优秀 Boost.Python 库:通过使用编译时自省来推断类型信息,从而最大限度地减少传统扩展模块中的样板代码。

安装:

brew install pybind11

参考官网的例子:example.cpp

#include 
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& pybind11::detail::load_type(pybind11::detail::type_caster&, pybind11::handle const&) in example-f398a2.o
  "__Py_NoneStruct", referenced from:
      pybind11::detail::type_caster& pybind11::detail::load_type(pybind11::detail::type_caster&, pybind11::handle const&) in example-f398a2.o
      pybind11::cpp_function::initialize_generic(std::__1::unique_ptr&&, 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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/836086.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号