2

I have been trying to figure out how to pass a fixed size array by reference using SWIG to python. Mostly I have been considering the numpy.i interface for this. However, I can't seem to find any reference to this online.

For regular array passing to numpy the way you do is it first the C++ function in foo.h:

void foo(double* array, int length);

And the relevant part of the SWIG file is:

%include "numpy.i"

%init %{
import_array();
%}

%apply (unsigned char* IN_ARRAY1, int DIM1) {(unsigned char* frame, int len)};

%include "foo.h"

The question is how do you perform this when the C++ function is:

void bar(double (&array)[3]);
1
  • I'm interested in a similar case: void func(double arr[3]) Commented Dec 3, 2015 at 19:09

1 Answer 1

1

This is a reference to an array of 3 doubles, right? According to 34.3.9 Pointers, references, values, and arrays, you should be able to use as is.

Otherwise, you could try 34.9.4 Mapping Python tuples into small arrays, or the section after that. Or provide further details in your question about what Python code you would like to be able to write vs the code you have to write if you just let SWIG export the bar() function as is, without typemaps.

Update: You should also be able to %extend or %inline an adapter function that forwards to the array version, something like:

%inline %{
    void bar(double* array, int length) {
         typedef double triplet[3]; // array of 3 doubles
         bar((triplet&)array); // shouldselect your bar since only one arg
    }
%}

Warning: not tested ;)

Sign up to request clarification or add additional context in comments.

2 Comments

It appears this is true, and should work well for build in Python datatypes! However, it still leaves open the question of how this works with numpy interface. I have only ever been able to find the (double *pointer, int len) method used when numpy.i is being used.
@Wilsonator Updated with possible other solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.