如何将 numpy ndarray 转换为 C float *[] [英] How to convert numpy ndarray to C float *[]
问题描述
我在 C
中有代码,我想在 python
中使用它,我使用 SWIG 来包装 C 代码,并且在我的python代码中成功导入了一个python模块.
I have code in C
, which I would like to use in python
, I used SWIG to wrap the C-code, and got successfully a python module imported in my python code.
现在我有以下代码:
import flame
import numpy as np
data = np.random.rand(3,2).astype(np.float32, copy=False)
N = 3
M = 2
print data
flameobject = flame.Flame_New()
flame.Flame_SetDataMatrix( flameobject, data, N, M, 0 )
这会产生错误:
TypeError: in method 'Flame_SetDataMatrix', argument 2 of type 'float *[]'
我知道我应该将 float 数组指针
传递给该方法,但是如何将我的 Numpy 多维数组转换为正确的类型?
I understand that I should pass a float array pointer
to the method, but how can I convert my Numpy multi-dimensional array into the correct type?
推荐答案
SciPy 文档正好说明了这一点:如何通过 SWIG 将 numpy 数组传递给 C 代码(反之亦然).看看这里.
There is SciPy documentation on exactly this: How to pass numpy arrays to C code via SWIG (and vice versa). Have a look here.
基本上,有一个 swig 接口文件 numpy.i
,您可以通过以下方式使用.在您的 swig 接口文件中,您包括:
Basically, there is a swig interface file numpy.i
that you use in the following way. In your swig interface file you include:
%{
#define SWIG_FILE_WITH_INIT
%}
%include "numpy.i"
%init %{
import_array();
%}
然后在你的接口文件中添加,在提到你的 C 函数之前:
and then add in your interface file, before mentioning your C functions:
%apply ( float* IN_ARRAY2, int DIM1, int DIM2 ) {
(float* your_array_parameter_name, int N_parameter_name, int M_parameter_name)
};
这适用于普通的 C float
数组.我不太确定 float* []
是什么.您可能需要为此编写自己的类型映射,为此您可以使用 numpy.i
提供的实用程序宏.但这一切都在上面提到的 numpy.i 文档或相关的 swig 中进行了解释类型映射文档
This works for ordinary C float
arrays. I am not quite sure what a float* []
is. You may need to write your own typemaps for this, for which you can use the utility macros provided by numpy.i
. But it is all explained in the numpy.i documentation mentioned above, or in the relevant swig typemap docs
这篇关于如何将 numpy ndarray 转换为 C float *[]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!