手把手python和C++交互,python调用C++程序并在python里显示c++的输出结果_pybind11

用pybind11,python和C++交互,python调用C++程序并在python里显示c++的输出结果。可以用于:已经有一个c++程序,想在python里显示这个c++程序的结果,在python里做一些运算(例如调用ML的库),并且可以返回给c++。相比与python的ctypes,pybind11方法支持更大的cpp程序,对现有的cpp兼容性更好。这个博客做到的是hands-on的python调用cpp的程序并在python里显示结果。

  1. 整个完成后的库也提供在我的github库里,这里提供了每一步的细节,可以一步一步照做。
    github库:https://github.com/798253405/Pybind11CppDemo

步骤:
2.1 找一个路径,创建一个文件夹,比如叫做pybind11Demo或者其他名字,在这个文件夹下,git下载 pybind文件:
在这里插入图片描述

git clone https://github.com/pybind/pybind11

下载完如下图。
在这里插入图片描述
2. 2 可选 为了方便,可以用clion新建一个项目,就用相同的路径。路径
clion会自动生成如下文件:
里面是一个helloword代码,无关紧要,只是为了一个配置方便的cmakelist.txt。
在这里插入图片描述

cmakelist.txt 里,cmake_minimum_required(VERSION 3.24) 这里的要求改为已安装的cmake版本,例如我是 3.22。
在这里插入图片描述

3.在pybind11Demo, cd 进入刚下载的pybind11

#
cd pybind11
mkdir build
cd build

cmake ..

出现以下结果。
在这里插入图片描述
4. 在pybind11Demo下,和下载的同级,创建一个cpp文件,文件名叫example.cpp

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

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

PYBIND11_MODULE(example, m)
{
// optional module docstring
m.doc() = "pybind11 example plugin";
// expose add function, and add keyword arguments and default arguments
m.def("add", &add, "A function which adds two numbers", py::arg("i")=1, py::arg("j")=2);

// exporting variables
    py::object theAnswer = py::cast("theAnswerShouldBe1+2=3");
m.attr("the_answer") = theAnswer;
py::object objectWorld = py::cast("World");
m.attr("what") =  objectWorld;
}
 

5.在文件夹example新建CMakeList.txt,并编辑。

cmake_minimum_required(VERSION 3.22)
project(example)
set(CMAKE_BUILD_TYPE "Release")
add_subdirectory(pybind11)
pybind11_add_module(example example.cpp)

这时候,文件夹长这样:
在这里插入图片描述
点击Clion的build。
在这里插入图片描述
在Pybind11CppDemo/cmake-build-debuild 文件夹下,应该有一个 example什么什么.so 文件。
在这里插入图片描述
在这个cmake-build-debug文件路径下,打开shell,python命令行import exmaple
如果没有安装pybind11 的python包,会报错。
的平
我们先用conda,安装 pybind11库:

conda info --env
conda activate torchgpuOffice202206 #换成你的环境名
conda install -c conda-forge pybind11

然后再打开命令行,输入python,输入:

import example
example.add(2023,9999)

结果如下图。
在这里插入图片描述

自此,我们 通过编译制造一个 example.so 文件,在python里可以调用一个c++的代码,并且在python里显示c++的运行结果。

ref1:https://blog.csdn.net/u012483097/article/details/108797976
ref2:https://pybind11.readthedocs.io/en/stable/advanced/pycpp/index.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值