继续聊上一个话题,这次我们要实现python对c++的常用容器的传参,直接上代码:
// pybind.cpp
#include <pybind11/pybind11.h> // pybind11的头文件
#include <pybind11/stl.h> // 需要包含该头文件,用于python的list,dict与C++中的容器的类型进行转换
#include <string>
#include <vector>
#include <tuple>
namespace py = pybind11; // 给pybind11命名空间名称用个简单的替换
PYBIND11_MODULE(pythondemo, m) // 定义Python模块,名称为pythondemo
{
m.def("use_string",
[](const std::string& str) // 入参是string
{
py::print(str);
return str + "!!"; // 返回string
}
);
m.def("use_tuple",
[](std::tuple<int, int, std::string> t) // 入参是tuple
{
std::get<0>(t)++;
std::get<1>(t)++;
std::get<2>(t)+= "??";
return t; // 返回元组
}
);
m.def("use_vector",
[](const std::vector<int>& v) // 入参是vector
{
auto list = v;
py::print("input :", list);
list.push_back(100);
return list; // 返回列表
}
);
}
通过g++ pybind.cpp -std=c++11 -shared -fPIC python3 -m pybind11 --includes
-o pythondemopython3-config --extension-suffix
编译生成目标动态库。
python部分的代码如下:
import pythondemo # 导入pybind11模块
print(pythondemo.use_string("hello c++"))
mytuple = 1, 2, "hello C++"
print(pythondemo.use_tuple(mytuple))
print(pythondemo.use_vector([1, 2, 3]))
得到的结果如下:
如果用class的方式,怎么调用呢?
#include <pybind11/pybind11.h> // pybind11的头文件
#include <pybind11/stl.h> // 需要包含该头文件,用于python的list,dict与C++中的容器的类型进行转换
#include <string>
#include <vector>
#include <tuple>
#include <iostream>
namespace py = pybind11; // 给pybind11命名空间名称用个简单的替换
class Student //就只是定义了一个学生类型
{
public:
Student() = default;
Student(std::string name)
{
std::cout << "my name is " << name << std::endl;
m_name = name;
}
void setId(int id) // 设置学生的学号
{
py::print("set the student's id to ", id);
m_Id = id;
}
int getId() // 获取学生的学号
{
return m_Id;
}
private:
std::string m_name;
int m_Id = 0;
};
PYBIND11_MODULE(pythondemo, m) // 定义Python模块,名称为pythondemo
{
py::class_<Student>(m, "Student")
.def(py::init()) // 导出构造函数
.def(py::init<std::string>()) // 导出构造函数
.def("setId", &Student::setId) // 导出成员函数,对于成员函数必须加上取地址符&
.def("getId", &Student::getId); // 导出成员函数
}
python部分代码如下:
import pythondemo # 导入pybind11模块
stu = pythondemo.Student("C++")
stu.setId(10)
print(stu.getId())
结果如下:
相信大家应该都能掌握怎么让python调用C++的容器,以及class类。对于python调用C++接口的基础知识,可以参考我的博文:[通过pybind11来实现python调用C++接口(一)]。(https://blog.csdn.net/shouqi321/article/details/130439525)