Skip to content

pybind11中数组类成员的使用

C++

cpp
#include <pybind11/pybind11.h>
#include <pybind11/stl.h> // 自动转换 std::array<>

namespace py = pybind11;

struct Student
{
	int id;
	std::string name;
};

struct ClassRoom
{
	std::array<Student, 10> students; // Right
	// Student students[10]; // Error
};

PYBIND11_MODULE(pytest, m) {

	py::class_<Student>(m, "Student")
		.def(py::init())
		.def_readwrite("id", &Student::id)
		.def_readwrite("name", &Student::name);

	py::class_<ClassRoom>(m, "ClassRoom")
		.def(py::init())
		.def_readwrite("students", &ClassRoom::students);
}

Python

python
# ===================================================
# 学习pybind11的使用
# ===================================================
import pytest

class_room = pytest.ClassRoom()
class_room.students[2].name = "Tom"

参考文献

  1. https://github.com/pybind/pybind11/issues/2149