- 前言
- 一、原理
- 二、py_list封装
- 三,测试
前言
本文是为了便于操作C++,在C++中封装啦python list类的全部函数,方便在C++中操作
一、原理本文采用pybind11重新包装python中的list,并补充一些功能,便于在C++中操作。
注意:由于内容较多其他文档另文说明。
二、py_list封装 1.头文件py_list.h#pragma once
#include "py_object.h"
class py_list : public py_object {
private:
py::list _lst;
public:
py_list() = default;
py_list(const size_t& num);
py_list(const py_list& b);
py_list(const py::list& b);
py_list(py_list&& b) noexcept;
py_list(py::list&& b) noexcept;
~py_list() = default;
py_list& operator=(const py_list& b);
py_list& operator=(const py::list& b);
py_list& operator=(py_list&& b) noexcept;
py_list& operator=(py::list&& b) noexcept;
py::object operator[](size_t index) const;
py::detail::list_accessor operator[](size_t index);
py_list operator+(const py::list& b);
py_list operator+(const py_list& b);
/
py_list::py_list(const size_t& num)
: py_object{py::list(num)}, _lst{py::list(num)} {}
py_list::py_list(const py_list& b) : py_object{b._obj} {
if (this != &b) _lst = b._lst;
}
py_list::py_list(const py::list& b) : py_object{b}, _lst{b} {}
py_list::py_list(py_list&& b) noexcept : py_object{b} {
if (this != &b) _lst = std::move(b._lst);
}
py_list::py_list(py::list&& b) noexcept : py_object{b}, _lst{std::move(b)} {}
py_list& py_list::operator=(const py_list& b) {
if (this != &b) {
_lst = b._lst;
_obj = _lst;
}
return *this;
}
py_list& py_list::operator=(const py::list& b) {
if (&this->_lst != &b) {
_lst = b;
_obj = _lst;
}
return *this;
}
py_list& py_list::operator=(py_list&& b) noexcept {
if (this != &b) {
_lst = b._lst;
_obj = _lst;
}
return *this;
}
py_list& py_list::operator=(py::list&& b) noexcept {
if (&this->_lst != &b) {
_lst = b;
_obj = _lst;
}
return *this;
}
py::object py_list::operator[](size_t index) const {
//return __getitem__(index);
return _lst[index];
}
py::detail::list_accessor py_list::operator[](size_t index) {
auto rst = _lst[index];
_obj = _lst;
return rst;
}
py_list py_list::operator+(const py::list& b) { return py_list(_lst + b); }
py_list py_list::operator+(const py_list& b) { return py_list(_lst + b._lst); }
/
三,测试
#include#include #include #include #include #include "py_object.h" #include "py_list.h" using std::cout; using std::endl; int main() { py::scoped_interpreter guard{}; test_pylist(); }



