[英]How to convert C array to Python tuple or list with SWIG?
I am developing a C++/Python library project which uses SWIG when converting the C++ code to the Python library. 我正在开发一个C ++ / Python库项目,它在将C ++代码转换为Python库时使用SWIG。 In one of C++ headers, I have some global constant values as below.
在C ++标题之一中,我有一些全局常量值,如下所示。
const int V0 = 0;
const int V1 = 1;
const int V2 = 2;
const int V3 = 3;
const int V[4] = {V0, V1, V2, V3};
I can use V0 to V3 directly from Python, but cannot access the entries in V
. 我可以直接从Python使用V0到V3,但不能访问
V
的条目。
>>> import mylibrary
>>> mylibrary.V0
0
>>> mylibrary.V[0]
<Swig Object of type 'int *' at 0x109c8ab70>
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'SwigPyObject' object has no attribute '__getitem__'
Could anyone tell me how to automatically convert V
to a Python tuple or list? 谁能告诉我如何自动将
V
转换为Python元组或列表? What should I do in my .i
file? 我的
.i
文件应该怎么办?
The following macro did work. 以下宏确实有效。
%{
#include "myheader.h"
%}
%define ARRAY_TO_LIST(type, name)
%typemap(varout) type name[ANY] {
$result = PyList_New($1_dim0);
for(int i = 0; i < $1_dim0; i++) {
PyList_SetItem($result, i, PyInt_FromLong($1[i]));
} // i
}
%enddef
ARRAY_TO_LIST(int, V)
%include "myheader.h"
If you don't want to create a typemap you can use the swig library carrays.i to access the entries in a C-type array. 如果您不想创建类型映射 ,可以使用swig库carrays.i来访问C类型数组中的条目。
your .i file would be something like: 你的.i文件是这样的:
%{
#include "myheader.h"
%}
%include "carrays.i"
%array_functions(int,intArray)
%include "myheader.h"
and then you could access mylibrary.V[0] in python with: 然后你可以在python中访问mylibrary.V [0]:
>>> intArray_getitem(mylibrary.V, 0)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.