在Swig中通过引用返回动态数组

2024-05-15 10:43:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用swig用c++包装一些代码,以便在Python中使用。
我有一个函数,它获取数组,并在对输入数组进行一些计算后返回2个动态数组。
我的问题是输出数组的大小是未指定的,因为大小取决于输入数组。
我的功能如下:

void arrayManipulate(int* inArray, int inLen, int resolution, int* &outArray1, int &outLen1, int* &outArray2, int &outLen2)

我使用numpy.I将输入数组强制转换为numpy数组。
但是如果我想使用numpy返回带有ARGOUT的数组,它就不起作用了,因为它假设输出数组的大小是已知的。在

模块一:

^{pr2}$

如果我试图编译这个,我会得到如下错误:

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 **"

如果我从minimal.I和minimal.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)

我该怎么做?在


Tags: of函数numpyvaluetypenotcxx数组
1条回答
网友
1楼 · 发布于 2024-05-15 10:43:58

这里有一个答案,它使用双指针而不是*&;。您可以创建一个简单的包装器函数来支持这个原型

确保在Python映射中被删除的数组将在被删除时生成。他们是被管理的

头文件(test.h):

#pragma once

void fun(int* inArray, int inLen, int resolution,
     int** outArray1, int* outLen1,
     int** outArray2, int* outLen2);

源文件(测试.cpp)公司名称:

^{pr2}$

接口定义文件(test.i)

%module example
%{
  #define SWIG_FILE_WITH_INIT
  #include "test.h"
%}

%include "numpy.i"

%init
%{
  import_array();
%}

%apply (int* IN_ARRAY1, int DIM1) {(int* inArray, int inLen)}

%apply (int** ARGOUTVIEWM_ARRAY1, int* DIM1) {(int** outArray1, int* outLen1)}
%apply (int** ARGOUTVIEWM_ARRAY1, int* DIM1) {(int** outArray2, int* outLen2)}

%include "test.h"

从Python内部

import numpy as np
import example
a = np.ones(27,dtype=np.int32)
h = example.fun(a,2) # h contains the two outputs

要支持例如size\t,请在numpy.i中搜索此部分

%numpy_typemaps(unsigned long long, NPY_ULONGLONG, int)
%numpy_typemaps(float             , NPY_FLOAT    , int)
%numpy_typemaps(double            , NPY_DOUBLE   , int)

并添加以下内容

%numpy_typemaps(signed char       , NPY_BYTE     , size_t)
%numpy_typemaps(unsigned char     , NPY_UBYTE    , size_t)
%numpy_typemaps(short             , NPY_SHORT    , size_t)
%numpy_typemaps(unsigned short    , NPY_USHORT   , size_t)
%numpy_typemaps(int               , NPY_INT      , size_t)
%numpy_typemaps(unsigned int      , NPY_UINT     , size_t)
%numpy_typemaps(long              , NPY_LONG     , size_t)
%numpy_typemaps(unsigned long     , NPY_ULONG    , size_t)
%numpy_typemaps(long long         , NPY_LONGLONG , size_t)
%numpy_typemaps(unsigned long long, NPY_ULONGLONG, size_t)
%numpy_typemaps(float             , NPY_FLOAT    , size_t)
%numpy_typemaps(double            , NPY_DOUBLE   , size_t)

这增加了更多的类型映射来支持使用size\u而不是int进行索引

相关问题 更多 >