SWIG C++ to Python:生成 Python 列表的子类
SWIG C++ to Python: generate a subclass of Python list
我正在使用SWIG(v3(将C++代码包装到Python 3。在C++中,我有一个从std::vector
继承的类MyClass
。我想把它包装在Python中,这样生成的Python类MyClass
是标准Python list
类的子类。这可能吗?
下面是一个示例:
例子.h
#include <vector>
#include <iostream>
using namespace std;
// List class
class MyList : public vector<int>
{
public:
// Init
MyList() : vector<int>() {
this->insert(this->begin(),2);
this->insert(this->begin(),1);
}
// Toy insert function
void toy_insert()
{
this->insert(this->begin(),0);
}
};
示例.cpp
#include "example.h"
例子.i
%module example
%{
#include "example.h"
%}
%include "std_vector.i"
using namespace std;
%template(MyVector) std::vector<int>; // Nothing known about base class 'vector< int >' if we remove std:: here
%typemap(out) MyList* {
int size = (*$1).size();
$result = PyList_New(size);
for (int i=0; i<size; i++) {
PyList_SetItem($result, i, PyInt_FromLong((*$1)[i]));
}
};
// List class
class MyList : public std::vector<int> // Nothing known about base class 'vector< int >' if we remove std:: here
{
public:
MyList();
void toy_insert();
};
run_example.py
import example
my_list = example.MyList()
print(my_list)
打印命令返回<example.MyList; proxy of [1, 2] >
,但这不是我想要的。理想情况下,这应该只返回[1,2]
,但随后我仍然可以调用:
my_list.toy_insert()
print(my_list)
应该返回[0,1,2]
.
感谢您的帮助
正如我在评论中提到的,您可以覆盖 SWIG 类型的显示。 下面是一个粗略的示例:
%module x
%{
#include "example.h"
%}
%include <windows.i>
%include <std_vector.i>
%template(MyVector) std::vector<int>;
%include "example.h"
%extend MyList {
const char*__repr__()
{
// I was lazy.
return "fancy representation";
}
}
输出:
>>> import x
>>> t=x.MyList()
>>> t
fancy representation
>>> t[0]
1
>>> t[1]
2
>>> t.toy_insert()
>>> t[0]
0
>>> t[1]
1
>>> t[2]
2
相关文章:
- 如何在C++中使用pybind11加载一个pickle python列表
- 从 std::vector<double> 到 Python 列表的转换失败(提升 python)
- 在C++中创建 python "列表"
- 将 std::list of structs 转换为 Python 列表
- 如何使用 Swig 将无符号字符* 转换为 Python 列表
- SWIG C++ to Python:生成 Python 列表的子类
- 用eCmascript Regex验证Python列表索引语法
- 如何有效地将 2d python 列表馈送到 c++ 扩展模块
- SWIG 类型映射的 python 列表到双倍 *
- 如何传递 python 列表地址
- 如何使用SWIG将C 数组转换为Python列表
- 在 C++ 提升 Python 列表中附加整数的错误
- 包装一个使用char**[in/out]的C函数调用,以在cython中返回一个python列表
- 使用SWIG和Python/C API来包装一个函数,该函数采用C++类实例的Python列表
- 将递归Python列表生成器转换为C++
- 如何使用ctypes将python列表传递给C函数(dll)
- c++中是否有任何数据结构或库可以像Python列表和字典一样工作?
- c++(类似于python列表)
- 从c++修改python列表
- 将python列表包装为unsigned char*