// SWIG includes for use in heasp.i // numpy code copied from https://github.com/dblalock/swig-numpy-example %include "typemaps.i" %include "std_string.i" %include "std_vector.i" %{ #define SWIG_FILE_WITH_INIT %} %include "numpy.i" %init %{ import_array(); %} // ------------------------------------------------ // vector typemaps // ------------------------------------------------ %define %np_vector_typemaps(DTYPE, NPY_DPTYE) namespace std { %typemap(out, fragment="NumPy_Fragments") vector { // create python array of appropriate shape npy_intp sz = static_cast($1.size()); npy_intp dims[] = {sz}; PyObject* out_array = PyArray_SimpleNew(1, dims, NPY_DPTYE); if (! out_array) { PyErr_SetString(PyExc_ValueError, "vector wrap: unable to create the output array."); return NULL; } // copy data from vect into numpy array DTYPE* out_data = (DTYPE*) array_data(out_array); for (size_t i = 0; i < sz; i++) { out_data[i] = static_cast($1.data()[i]); } $result = out_array; } %typemap(out, fragment="NumPy_Fragments") vector& { // create python array of appropriate shape npy_intp sz = static_cast((*$1).size()); npy_intp dims[] = {sz}; PyObject* out_array = PyArray_SimpleNew(1, dims, NPY_DPTYE); if (! out_array) { PyErr_SetString(PyExc_ValueError, "vector wrap: unable to create the output array."); return NULL; } // copy data from vect into numpy array DTYPE* out_data = (DTYPE*) array_data(out_array); for (size_t i = 0; i < sz; i++) { out_data[i] = static_cast((*$1).data()[i]); } $result = out_array; } %typemap(in, fragment="NumPy_Fragments") vector& (vector tvec) { // a Python array is in $input. We need to get its size then resize // $1 and copy the contents from $input into $1. int is_new_object = 0; PyArrayObject* array = obj_to_array_contiguous_allow_conversion($input, NPY_DPTYE, &is_new_object); if (!array || !require_dimensions(array, 1)) SWIG_fail; size_t size = array_size(array, 0); tvec.resize(size); // copy data from numpy array into vector DTYPE* in_data = (DTYPE*) array_data(array); for (size_t i = 0; i < size; i++) { tvec[i] = static_cast(in_data[i]); } $1 = &tvec; } } %enddef %np_vector_typemaps(int, NPY_INT) %np_vector_typemaps(long, NPY_LONG) %np_vector_typemaps(float, NPY_FLOAT) %np_vector_typemaps(double, NPY_DOUBLE) //%template(IntVector) vector; //%template(FloatVector) vector; //%template(DoubleVector) vector; // StringVector is just a python list %template(StringVector) vector;