【问题标题】:TypeError when passing 2d numpy array to C++将 2d numpy 数组传递给 C++ 时出现 TypeError
【发布时间】:2013-08-16 09:54:44
【问题描述】:

我在 numpyarray 和 C++ 代码中有二维数据,我想对这些数据执行一些操作。使用 swig 和 distutils 以及 numpy.i 我设法将所有内容编译成 python 扩展“goldstein”,它提供了一个函数unwrap2d。 我使用它测试它

import goldstein

data = np.ascontiguousarray(data_temp, dtype='double')
mask = np.ascontiguousarray(mask_temp, dtype='uint16')
outdata = np.ones_like(data)

goldstein.unwrap2d(data,mask,outdata)

我收到了TypeError: array cannot be safely cast to required type。谁能指出我如何以正确的方式传递这些数组?

供参考:为了创建模块,我使用了接口文件

%define DOCSTRING
"Wrapper for c++-code"
%enddef

%module(docstring=DOCSTRING) goldstein

%{
    #define SWIG_FILE_WITH_INIT
    #include "goldstein.h"
%}

/*include numpy typemaps*/
%include "numpy.i"
/*initialize module*/
%init %{
    import_array();
%}

%rename(unwrap2d) phase_unwrapping_func;

/* typemaps for the arrays*/
%apply (int DIM1,int DIM2,float* IN_ARRAY2) {(int xsize,int ysize,float* in)};
%apply (int DIM1,int DIM2,unsigned short* IN_ARRAY2) {(int x1,int y1,unsigned short* mask)};
%apply (int DIM1,int DIM2,float* INPLACE_ARRAY2) {(int x2,int y2,float* out)};

/*wrapper function calling the original phase_unwrapping using only the needed parameters*/
%inline %{
void phase_unwrapping_func(int xsize,int ysize,float* in,int x1,int y1,unsigned short* mask,int x2,int y2,float* out) {
    phase_unwrapping(xsize, ysize, in, mask, out);
    }
%}

【问题讨论】:

  • 我尝试打开语法高亮,但没有成功... :(
  • 您的 data 数组是双精度数据类型,但您的 C 函数需要浮点数。这可能就是让 NumPy 抱怨的原因。在调用你的函数之前执行data = np.ascontiguousarray(data_temp, dtype='float') 应该注意这一点。

标签: arrays numpy swig


【解决方案1】:

@Jaimie 当然是对的。像'double'这样的'float'在numpy中是64位的,这就是我没有再次检查的原因,我只记得没关系。但是 c++ 中的 float 显然需要 32 位,在 numpy 中是 'float32'。 谢谢!

【讨论】:

    猜你喜欢
    • 2014-04-20
    • 2022-01-14
    • 1970-01-01
    • 1970-01-01
    • 2022-01-03
    • 2010-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多