SWIG Python fixed size array passed by reference

[亡魂溺海] 提交于 2019-12-12 19:31:56

问题


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:


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 ;)



来源:https://stackoverflow.com/questions/22498128/swig-python-fixed-size-array-passed-by-reference

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!