SWIG/python数组内部结构

SWIG/python数组内部结构,python,arrays,swig,Python,Arrays,Swig,我在header.h中定义了一个结构,它看起来像: typedef struct { .... int icntl[40]; double cntl[15]; int *irn, *jcn; .... 当我用这种结构初始化一个对象时,我可以访问整数/双精度数,但不能访问数组 >> st.icntl <Swig Object of type 'int *' at 0x103ce37e0> >> st.icntl[

我在header.h中定义了一个结构,它看起来像:

typedef struct {
....
    int      icntl[40];
    double   cntl[15];
    int      *irn, *jcn;
....
当我用这种结构初始化一个对象时,我可以访问整数/双精度数,但不能访问数组

>> st.icntl
<Swig Object of type 'int *' at 0x103ce37e0>
>> st.icntl[0]
Traceback (most recent call last):
  File "test_mumps.py", line 19, in <module>
    print s.icntl[0]
TypeError: 'SwigPyObject' object is not subscriptable
>st.icntl
>>圣约翰岛[0]
回溯(最近一次呼叫最后一次):
文件“test_mumps.py”,第19行,在
打印s.icntl[0]
TypeError:“SwigPyObject”对象不可下标

如何访问读/写中的值?

最简单的方法是将数组封装在结构中,然后该结构可以提供

我举了一个小例子。它假设你使用C++,但是等效C版本是非常微不足道的,因此它只需要一点点重复。

首先,具有<代码>结构> <代码>的C++头,我们要包装和使用一个模板来包装固定大小数组:

template <typename Type, size_t N>
struct wrapped_array {
  Type data[N];
};

typedef struct {
    wrapped_array<int, 40> icntl;
    wrapped_array<double, 15> cntl;
    int      *irn, *jcn;
} Test;

您也可能会发现,作为一种替代方法,它非常有用/有趣。

我会用python来完成这项工作

ptr = int(st.icntl)
import ctypes
icntl = ctypes.c_int * 40
icntl = icntl.from_address(ptr)

print icntl[0]
icntl[0] = 1
for i in icntl:
    print i 

您是否考虑过使用SWIG carrays

在头文件中:

typedef struct {
    int      icntl[40];
    double   cntl[15];
} some_struct_t;
然后,在swig文件中:

%module example
%include "carrays.i"  
// ...
%array_class(int, intArray);
%array_class(double, doubleArray);
Python如下所示:

icntl = example.intArray(40)
cntl = example.doubleArray(15)
for i in range(0, 40):
    icntl[i] = i
for i in range(0, 15):
    cntl[i] = i
st = example.some_struct_t()
st.icntl = icntl
st.cntl = cntl
您仍然无法直接设置结构。我编写python包装器代码来隐藏样板文件

array_类仅适用于基本类型(int、double),如果需要其他类型(例如uint8_t),则需要使用array_函数,这些函数有更多的样板文件,但它们可以工作

%module example
%include "carrays.i"  
// ...
%array_class(int, intArray);
%array_class(double, doubleArray);
icntl = example.intArray(40)
cntl = example.doubleArray(15)
for i in range(0, 40):
    icntl[i] = i
for i in range(0, 15):
    cntl[i] = i
st = example.some_struct_t()
st.icntl = icntl
st.cntl = cntl