structu中的SWIG/python数组

2024-09-30 01:27:21 发布

您现在位置:Python中文网/ 问答频道 /正文

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

typedef struct {
....
    int      icntl[40];
    double   cntl[15];
    int      *irn, *jcn;
....

当我用这个结构初始化一个对象时,我可以访问整数/双精度数,但不能访问数组。在

^{pr2}$

如何访问读/写中的值?在


Tags: 对象定义精度整数数组结构structint
3条回答

我会用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文件中:

^{pr2}$

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_函数,这些函数有更多的样板文件,但它们可以工作。在

http://www.swig.org/Doc3.0/SWIGDocumentation.html#Library_carrays

最简单的方法是将数组包装在struct中,然后它可以提供extra methods to meet the "subscriptable" requirements。在

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

首先,我们要包装的^ + {CD1>}的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;

相应的SWIG接口看起来像:

^{pr2}$

这里的技巧是我们使用%extend来提供^{},这是Python用于下标读取和{a3}用于写入的。(我们还可以提供一个__iter__使类型可迭代)。我们还提供了特定的wraped_array,我们希望使用唯一的名称使SWIG将它们包装在输出中。在

通过提供的接口,我们现在可以:

>>> import test
>>> foo = test.Test()
>>> foo.icntl[30] = -654321
>>> print foo.icntl[30]
-654321
>>> print foo.icntl[40]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "test.py", line 108, in __getitem__
    def __getitem__(self, *args): return _test.intArray40___getitem__(self, *args)
IndexError: out of bounds access

您还可能会发现this approach是一种有用/有趣的替代方案。在

相关问题 更多 >

    热门问题