简体   繁体   English

Python / SWIG:按索引返回数组

[英]Python/SWIG: Return Array by Index

I am trying to output an array of values from a C++ function wrapped using SWIG for Python. 我正在尝试从使用SWIG for Python包装的C ++函数输出值数组。 I know how to do this for the simple case of returning a C++ array using the following typemap: 我知道如何使用以下类型映射返回C ++数组的简单情况:

%apply (double* ARGOUT_ARRAY1, int DIM1) {(double* output_array, int length)};

with the associated C++ code looking like: 关联的C ++代码如下所示:

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: Python的用法如下:

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: 因此,C ++代码如下所示:

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. 我也知道在这种情况下返回数组的大小将是6的两倍,但是我不确定如何将该信息中继到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 . 这将匹配参数double* output_arrayMyClass::retrieveArray int length To call the function from python, use: 要从python调用函数,请使用:

output_array = my_class_instance.retrieveArray(length, index)

or, since you already know that the length will be 6: 或者,因为您已经知道长度为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: 如果您在编译时已经知道数组的大小,也可以修改C ​​++代码以使用以下函数签名:

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. 另请参阅numpy.i文档 ,我认为您正在使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM