在Cython中向/从函数传递输入/输出 [英] Passing Input/Output to/from functions in Cython
问题描述
我正在尝试在cython中编写一个函数,该函数应该从python接收一个list参数,方法是通过在C / C ++中生成它的2D数组,然后以2D列表的形式返回给python,从而以某种方式对其进行操作。我简化了代码,问了我的问题:
I am trying to write a function in cython which should receive a list argument from python manipulate it in some way by generating a 2D array of it in C/C++ and then return it to python as a 2D list. I simplified the code to ask my question:
我希望 c_Func
可以执行无需编译的过程错误。第二个函数是可调用函数,但显然不起作用。首先,我必须处理不能用 double * 替换列表的问题,其次是
py_Func
无法返回 double *
。那么我应该如何更改这两个呢?
I expect c_Func
to do the procedure which I can compile it without error. The second function is the callable function but obviously it doesn't work. First I have to deal with the problem that a list cannot be replaced by a double*
and second it the problem that py_Func
can't return a double*
. So how should I change these two?
cdef double** c_Func(int dim,double* init_val):
cdef double** frozen_ans= <double**> malloc(dim*sizeof(double))
frozen_ans[0]=init_val
return frozen_ans
def py_Func(int dim, double* init_val):
return c_Func(dim,init_val)
推荐答案
我假设您要操作来自C / C ++。
I assume that you want to manipulate the data from C/C++.
请勿使用malloc,因为稍后您将无法释放该指针,并且代码将泄漏内存。取而代之的是使用可以稍后由python处理的容器,例如numpy数组。
Do not use malloc, as you're not going to be able to free that pointer later, and your code will leak memory. Use instead a container that can be handled later by python, like a numpy array for example.
使用'handle'是指当numpy数组以
With 'handle' I mean the fact that when the numpy array ends up in the python garbage collector, python will deallocate that memory block for you.
扩展numpy选项,您可以创建一个连续的c样式numpy数组& arr [0]
(如(不为空),然后将其作为python numpy.ndarray
对象返回。请参阅此,以方便numpy对象访问。这样做的优点是 arr
可以被c代码当作ac数组。
Expanding on the numpy option, you can create a contiguous, c-style numpy array arr
from within cython, fill it/use it as a c array from pure c code using its address &arr[0]
(as long as it's not empty), and then return it as a python numpy.ndarray
object. See this on numpy objects convenient access. This has the strong advantage that arr
and can be treated as a c array from c code.
您的cython函数,如果您不想返回一个numpy数组,则可以使用 arr.tolist()
方法,但这会产生开销,因为您创建新列表。
At the end of your cython function, if you don't want to return a numpy array, you can use arr.tolist()
method, but this will incur in a overhead, because you are creating a new list.
关于输入部分,您说您的函数必须接受python列表。它可以是:
Regarding the input part, you say your function must accept a python list. It could either:
- 接受一个numpy数组,对其进行操作并返回它。
- 接受一个python列表
l
,将其转换为具有np.ascontiguousarray(l)
的numpy数组,对其进行处理并返回。在这种情况下,您会产生复制开销,但是您几乎无能为力。
- accept a numpy array, manipulate it and return it.
- accept a python list
l
, cast it to a numpy array withnp.ascontiguousarray(l)
, manipulate it and return it. In this case you're incurring in a copy overhead, but there's little you can about it.
这篇关于在Cython中向/从函数传递输入/输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!