I am trying to output an array of values from a C++ function wrapped using SWIG for Python. I know how to do this for the simple case of returning a C++ array using the following typemap:
%apply (double* ARGOUT_ARRAY1, int DIM1) {(double* output_array, int length)};
with the associated C++ code looking like:
void MyClass::retrieveArray(double* output_array, int length) {
for (int i=0; i<length; i++)
output_array[i] = _array[i];
}
The usage from Python looks like:
output_array = my_class_instance.returnArray(length)
However, I want to take this a step further and return an array using an index into a multi-dimensional array. So the C++ code would look like:
void MyClass::retrieveArray(double* output_array, int length, int index) {
for (int i=0; i<length; i++)
output_array[i] = _multi_dimensional_array[index][i];
}
However, the typemap would need to be changed to accommodate the index. I have tried:
%apply (double* ARGOUT_ARRAY1, int DIM1, int index) {(double* output_array,
int length, int index)};
but that does not seem to work. I also know that the size of the returned array in this case will be 6 doubles, but I am not sure how to relay that information to SWIG.
You should be able to apply the same typemap as before:
%apply (double* ARGOUT_ARRAY1, int DIM1) {(double* output_array, int length)};
This will match the parameters double* output_array
and int length
of MyClass::retrieveArray
. To call the function from python, use:
output_array = my_class_instance.retrieveArray(length, index)
or, since you already know that the length will be 6:
output_array = my_class_instance.retrieveArray(6, index)
You can also modify your C++ code to use the following function signature if you already know the size of the array at compile time:
void MyClass::retrieveArray(double output_array[6], int index) {...}
and then use a different typemap:
%apply (double ARGOUT_ARRAY1[6]) {(double output_array[6])};
See also the documentation for numpy.i , which I assume you are using.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.