【发布时间】:2016-07-06 10:48:33
【问题描述】:
我正在使用 swig 在 c++ 中包装一些代码以在 Python 中使用。
在对输入数组进行一些计算后,我有一个获取数组并返回 2 个动态数组(该函数通过 ref 获取它们)的函数。
我的问题是输出数组的大小未指定,因为大小取决于输入数组。
我的功能看起来像:
void arrayManipulate(int* inArray, int inLen, int resolution, int* &outArray1, int &outLen1, int* &outArray2, int &outLen2)
我使用 numpy.i 将输入数组转换为 numpy 数组。
但是如果我想使用 numpy 来返回带有 ARGOUT 的数组,它就不起作用,因为它假设输出数组的大小是已知的。
模块.i:
%module minimal
%{
#include "minimal.h"
#include "numpy/arrayobject.h"
%}
%include numpy.i
%init %{
inport_array();
%}
%apply (int* INARRAY1, int DIM1) {(int* inArray, int inLen)}
%apply (int* ARGOUT_ARRAY1, int DIM1) {(int* &outArray1, int &outLen1), (int* &outArray2, int &outLen2)
%include "minimal.h"
如果我尝试编译它,我会收到以下错误:
File minimal_wrap.cxx: IntelliSense: a value of type "int" could not be assigned to entity od type "int *"
File minimal_wrap.cxx: IntelliSense: a value of type "int *" could not be assigned to entity od type "int **"
如果我从 minimum.i 和 minimum.h(从函数)中删除所有“&”符号,它会编译,但 python 除外以给出输出数组的维度:
TypeError: arrayManipulate takes exactly 4 arguments (2 given)
我想在 python 中使用它,例如:
import minimal
import numpy as np
arr1, arr2 = minimal.arrayManipulate(np.asarray([1,2,3]),100)
我怎样才能让它工作?
【问题讨论】:
-
看来您需要
ARGOUTVIEW_ARRAY1类型映射。 -
将您的签名更改为
(int* inArray, int inLen, int resolution, int** outArray1, int* outLen1, int** outArray2, int *outLen2)并使用ARGOUTVIEW_ARRAY1甚至更好的ARGOUTVIEWM_ARRAY1。返回一个带有托管数据的 NumPy 数组。
标签: python c++ arrays numpy swig