<p>最简单的方法是将数组包装在<code>struct</code>中,然后它可以提供<a href="https://stackoverflow.com/questions/216972/in-python-what-does-it-mean-if-an-object-is-subscriptable-or-not">extra methods to meet the "subscriptable" requirements</a>。在</p>
<p>我举了一个小例子。它假设你使用C++,但是等效C版本是相当微不足道的,因此它只需要一点点重复。在</p>
<p>首先,我们要包装的^ + {CD1>}的C++头和用于包装固定大小数组的模板:</p>
<pre><code>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;
</code></pre>
<p>相应的SWIG接口看起来像:</p>
^{pr2}$
<p>这里的技巧是我们使用<code>%extend</code>来提供<a href="http://docs.python.org/reference/datamodel.html#object.__getitem__" rel="nofollow noreferrer">^{<cd4>}</a>,这是Python用于下标读取和{a3}用于写入的。(我们还可以提供一个<code>__iter__</code>使类型可迭代)。我们还提供了特定的<code>wraped_array</code>,我们希望使用唯一的名称使SWIG将它们包装在输出中。在</p>
<p>通过提供的接口,我们现在可以:</p>
<pre><code>>>> 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
</code></pre>
<p>您还可能会发现<a href="http://www.swig.org/Doc1.3/Python.html#Python_nn63" rel="nofollow noreferrer">this approach</a>是一种有用/有趣的替代方案。在</p>