python调用c++程序(pybind11)

前言

c或者c++代码的效率比python要高很多,所以,很多时候,python程序会有一部分使用c或者c++来实现。
本文介绍如何使用pybind11简单的包装c++程序,然后编译成一个python可以直接调用的模块。

pybind11的安装

pybind11的安装非常简单,你可以像安装一般的python包一样,使用pip来安装。

pip install pybind11

如果要安装在全局,/usr/local/include/pybind11路径,可以使用

pip install "pybind11[global]"

简单的使用示例

接下来演示一个简单的示例。首先编写一个c++函数,然后使用pybind11包装,编译成python模块。

//in the file test_pybind11
#include <pybind11/pybind11.h>
#include<iostream>
using namespace std;
int add(int i, int j,string str) {
    
    
    cout<<"The add function receive i = "<<i<<" j = "<<j<<" str "<<str<<endl;
    return i + j;
}
//the test is module name, you can use what you like, but must be same with last .so file prefix.
PYBIND11_MODULE(test, m) {
    
    
    m.doc() = "pybind11 example plugin"; // optional module docstring

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

m.def的第一个参数是python中模块的方法名,也就是在python中使用test.add来调用这个函数,第二个参数是一个函数指针(要编译成python方法的c++函数),第三个是该方法的注释,采用python中的help(test.add)的时候会出现的内容。
接下来,使用如下命令编译:

c++ -O3 -Wall -shared -std=c++11 -fPIC $(python3 -m pybind11 --includes) test_pybind11.cpp -o test$(python3-config --extension-suffix)

-o后面的test和代码中的模块名需要一致,不然会报错的。
最后会生成一个类似这样的后缀为.so的文件

test.cpython-38-x86_64-linux-gnu.so

前面的test是模块名,中间是版本信息,后缀为.so
下面可以在python中直接调用了。

#the version of python is python3.8
import test
res=test.add(1,2,"Hello")
print(res)

输出如下

The add function receive i = 1 j = 2 str Hello
3

猜你喜欢

转载自blog.csdn.net/watqw/article/details/124810424
今日推荐