//
// This SWIG module shows how C++ exceptions can be caught by Perl
// wrapper functions.

%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(perl5) {
  try {
    $function
  } 
  catch (RangeError) {
    croak("Array index out-of-bounds");
  }
}

// Just define our class in-line in the interest of laziness
	
%inline %{

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

    DoubleArray(int size) {
      ptr = new double[size];
      n = size;
    }
      
    // Destroy an array

    ~DoubleArray() {
       delete ptr;
    }
    
    // Return the length of the array

    int   length() {
      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();
      }
    }
  };

%}



syntax highlighted by Code2HTML, v. 0.9.1