ऐसा करने का सबसे आसान तरीका है struct
के अंदर अपने सरणी को लपेटना, जो extra methods to meet the "subscriptable" requirements प्रदान कर सकता है।
मैंने एक छोटा सा उदाहरण एक साथ रखा है। यह मानता है कि आप सी ++ का उपयोग कर रहे हैं, लेकिन समकक्ष सी संस्करण इस से निर्माण करने के लिए काफी छोटा है, इसे केवल दोहराव की आवश्यकता है।
सबसे पहले, सी ++ शीर्ष लेख struct
हम रैप करने के लिए करना चाहते हैं और है कि हम लपेटकर तय आकार सरणियों के लिए उपयोग एक टेम्पलेट है कि:
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;
हमारी इसी बड़ा घूँट इंटरफ़ेस तो लग रहा है कि:
%module test
%{
#include "test.h"
#include <exception>
%}
%include "test.h"
%include "std_except.i"
%extend wrapped_array {
inline size_t __len__() const { return N; }
inline const Type& __getitem__(size_t i) const throw(std::out_of_range) {
if (i >= N || i < 0)
throw std::out_of_range("out of bounds access");
return self->data[i];
}
inline void __setitem__(size_t i, const Type& v) throw(std::out_of_range) {
if (i >= N || i < 0)
throw std::out_of_range("out of bounds access");
self->data[i] = v;
}
}
%template (intArray40) wrapped_array<int, 40>;
%template (doubleArray15) wrapped_array<double, 15>;
चाल यह है कि हमने %extend
का उपयोग __getitem__
की आपूर्ति के लिए किया है जो कि पाइथन सबस्क्रिप्ट पढ़ने के लिए उपयोग करता है और __setitem__
लिखने के लिए उपयोग करता है। (हम टाइप करने योग्य बनाने के लिए __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 उपयोगी/दिलचस्प एक विकल्प के रूप मिल सकती है:
आपूर्ति इंटरफ़ेस अब हम क्या कर सकते हैं के साथ
।