[Numpy-discussion] [NumPy/Swig] Return NumPy array with same size as input array (no additional length argument)

laurentes laurentelshafey at gmail.com
Sat Oct 31 02:15:09 EDT 2015


Using Swig, I don't manage to (properly) create the Python Binding for the
following C-like function:

void add_array(double* input_array1, double* input_array2, double*
output_array, int length);

where the three arrays have all the same length.

This is similar to  this thread
, which has never been fully addressed online.

>From Python, I would like to be able to call:

add_array(input_array1, input_array2)

which would return me a newly allocated NumPy array (output_array) with the

In my Swig file, I've first used the wrapper function trick described  here
, that is:

%apply (double* IN_ARRAY1, int DIM1) {(double* input_array1, int length1),
(double* input_array2, int length2)};
%apply (double* ARGOUT_ARRAY1, int DIM1) {(double* output_array, int

%rename (add_array) my_add_array;
%exception my_add_array {
    if (PyErr_Occurred()) SWIG_fail;
%inline %{
void my_add_array(double* input_array1, int length1, double* input_array2,
int length2, double* output_array, int length3) {
  if (length1 != length2 || length1 != length3) {
                   "Arrays of lengths (%d,%d,%d) given",
                   length1, length2, length3);
  else {
    add_array(input_array1, input_array2, output_array, length1);

This allows me to call the function from Python using
add_array(input_array1, input_array2, length). But the third argument of
this function is useless and this function does not look 'Pythonic'.

Could someone help me to modify my Swig file, such that only the first two
arguments are required for the Python API?

Thanks a lot,

View this message in context: http://numpy-discussion.10968.n7.nabble.com/NumPy-Swig-Return-NumPy-array-with-same-size-as-input-array-no-additional-length-argument-tp41601.html
Sent from the Numpy-discussion mailing list archive at Nabble.com.

More information about the NumPy-Discussion mailing list