使用来自numpy.i的部分类型映射

using partial typemaps from numpy.i

本文关键字:类型 映射 numpy      更新时间:2023-10-16

我有一个函数只需要输入数组的一个维度,所以我忽略了2D numpy数组中的一个维度。有办法做到这一点吗?

头:

#ifndef __nparrtest_h__
#define __nparrtest_h__
class NPArrTest {
public:
    static void Print2D(int n, int m, const int* graph);
};
#endif

Cpp:

#include "NPArrTest.h"
#include <stdio.h>
void NPArrTest::Print2D(int n, int m, const int* graph) {
     printf("n: %d m: %dn",n,m);
}

swig接口文件:

%module NPArrTest
%{
    #define SWIG_FILE_WITH_INIT
    #include "NPArrTest.h"
%}
%include "numpy.i"
%init %{
  import_array1();
%}
%numpy_typemaps(int,    NPY_INT   , int)
//Something like the below:
%apply int DIM2, int* IN_ARRAY2 {int m, const int* graph};
%include "NPArrTest.h"

我不能让%apply (int DIM1, int* IN_ARRAY2) {(int m, const int* graph)};%apply int* IN_ARRAY2 {const int* graph};工作(梯子只是通过2D数组)。

如何传递二维数组的单一维度长度值到c++函数?

>

注:是否有一种简单的方法来允许这种转换?

TypeError:不能根据'safe'规则将数组数据从dtype('int64')强制转换为dtype('int32')

我对一个固定维度的输出数组做了类似的处理。下面的代码是我为numpy.i做的扩展的一部分。

#ifdef SWIGPYTHON
%{
#ifndef SWIG_FILE_WITH_INIT
#  define NO_IMPORT_ARRAY
#endif
#include "stdio.h"
#include <numpy/arrayobject.h>
%}
%include "numpy.i"
%define %numpy_ex_typemaps(DATA_TYPE, DATA_TYPECODE, DIM_TYPE)
/* Typemap suite for (DATA_TYPE** DYNARGOUTVIEW_ARRAY2_FIXED[ANY], DIM_TYPE* DIM1)
 */
%typemap(in,numinputs=0,noblock=1)
(DATA_TYPE* DYNARGOUTVIEW_ARRAY2_FIXED[ANY], DIM_TYPE* DIM1)
{
  size_t secondDim = $1_dim0;
  size_t firstDim;
  DATA_TYPE* tempData;
  $1 = &tempData;
  $2 = &firstDim;
}
%typemap(out)
void DYNARGOUTVIEW_ARRAY2_FIXED_##DATA_TYPECODE
{
  npy_intp dims[2] = {(npy_intp) firstDim, (npy_intp) secondDim};
%#ifdef __GNUC__
  __extension__
%#endif
  PyObject * array = PyArray_SimpleNewFromData(2, dims, DATA_TYPECODE,(void*)(tempData));
  if (!array) SWIG_fail;
  $result = SWIG_Python_AppendOutput($result,array);
}
%enddef    /* %numpy_ex_typemaps() macro */
%numpy_ex_typemaps(double            , NPY_DOUBLE   , size_t)
%numpy_ex_typemaps(float             , NPY_FLOAT    , size_t)
%numpy_ex_typemaps(signed char       , NPY_BYTE     , size_t)

当你应用这个类型映射时,你必须匹配两个类型映射,例如

%apply (double* DYNARGOUTVIEW_ARRAY2_FIXED[ANY], size_t* DIM1) {(double* coefs[3], size_t* length)};
%apply void DYNARGOUTVIEW_ARRAY2_FIXED_NPY_DOUBLE {void getFilter}

你的函数是这样的。

void getFilter(double* coefs[3], size_t* length);

从原始numpy中应该可以清楚地看到。