File: array.i

package info (click to toggle)
swig 1.1p5-1
  • links: PTS
  • area: main
  • in suites: hamm
  • size: 9,448 kB
  • ctags: 5,025
  • sloc: cpp: 21,599; ansic: 13,333; yacc: 3,297; python: 2,794; makefile: 2,197; perl: 1,984; tcl: 1,583; sh: 736; lisp: 201; objc: 143
file content (103 lines) | stat: -rw-r--r-- 1,924 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
//
// This SWIG module shows how you can create a Python array class in C++ 
// and catch C++ exceptions.

%module darray
%{

// Exception class
class RangeError { };

%}

// This defines a SWIG exception handler.   This code will be inserted
// into the wrapper code generated by SWIG.  The variable '$function' is
// substituted with the *real* C++ function call.

%except(python) {
  try {
    $function
  } 
  catch (RangeError) {
    PyErr_SetString(PyExc_IndexError,"index out-of-bounds");
    return NULL;
  }
}

// Just define our class in-line since it has been specifically designed
// for Python anyways.
	
%inline %{

  class DoubleArray {
  private:
    int n;
    double *ptr;
    int isslice;
  public:
    
    // Create a new array of fixed size

    DoubleArray(int size) {
      ptr = new double[size];
      n = size;
      isslice = 0;
    }

    // Create a slice (used internally)

#ifndef SWIG
    DoubleArray(double *pt,int size) {
      ptr = pt;
      n = size;
      isslice = 1;
    }
#endif
      
    // Destroy an array

    ~DoubleArray() {
      if (!isslice)
	delete [] ptr;
    }
    
    // Return the length of the array

    int    __len__() {
      return n;
    }
    
    // Get an item from the array and perform bounds checking.

    double __getitem__(int i) {
      if ((i >= 0) && (i < n))
	return ptr[i];
      else
	throw RangeError();
	return 0;
    }
    
    // Set an item in the array and perform bounds checking.

    void __setitem__(int i, double val) {
      if ((i >= 0) && (i < n))
	ptr[i] = val;
      else {
	throw RangeError();
      }
    }
    
    // Return a slice of this array.  
    DoubleArray __getslice__(int low,int high) {
      int i;
      if (low < 0) low = 0;
      if (low >= n) high = n;
      if (high < 0) high = 0;
      if (high >= n) high = n;
      if (low > high) low = high;
      return DoubleArray(ptr+low,high-low);
    }
  };

%}