pybind11 库

01 pybind11 库

pybind11 只需包含头文件,即可完成python与c++的相互调用。对编译要求较高。

pybind11\include\pybind11\detail\common.h
line60 error pybind11 requires Xcode/clang 5.0 or newer
line64 error pybind11 requires gcc 4.8 or newer
line70 error pybind11 requires MSVC 2015 update 3 or newer

github:https://github.com/pybind/pybind11
官网文档:http://pybind11.readthedocs.io/en/master/

最简单的example,保存在 https://github.com/5455945/cpp_demo

test03.py 调用 test01.cpp中的add方法。
test02.cpp调用 test04.py 中的add方法。

test01.cpp

#include <pybind11/pybind11.h>
namespace py = pybind11;

int add(int i, int j) {
    return i + j;
}

PYBIND11_MODULE(test01, m) {
    m.doc() = "pybind11 test01 plugin"; // optional module docstring

    m.def("add", &add, "A function which adds two numbers");

}

test03.py

import test01
print("test01.add(3, 4) = ", test01.add(3, 4))
print("test01.add(8, 9) = ", test01.add(8,9))

test02.cpp

#include <pybind11/embed.h>
#include <iostream>

namespace py = pybind11;

int main() {
    py::scoped_interpreter python;

    py::module sys = py::module::import("sys");
    py::print(sys.attr("path"));

    py::module t = py::module::import("test04");
    t.attr("add")(1, 2);
    return 0;
}

test04.py

"""test04.py located in the working directory"""
def add(i, j):
    print("hello,pybind11")
    return i + j

使用cmake-gui设置 python的头文件路径和lib库路径。即可。需要vs2015update3+。
这里写图片描述

运行结果
这里写图片描述

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值