用Cython:不能Python对象转换为“双*' [英] Cython: can't convert Python object to 'double *'

查看:468
本文介绍了用Cython:不能Python对象转换为“双*'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一个书面方式包装用Cython到C函数。我有以下签名的文件PXD:

 双contr_hrr(INT莉娜,双XA,双亚,双ZA,双* anorms)

当我尝试从PYX文件调用此

  ...
返回contr_hrr(LEN(acoefs),a.origin [0],a.origin [1],a.origin [2],anorms2)

其中 anorms2 是一个Python的名单,我得到错误信息:

 用Cython / ctwo.pyx:35:80:不能Python对象转换为双*'

我如何通过Python列表C函数作为双阵列?


解决方案

  1. cimport 阵列

     从CPython的cimport阵列


  2. 创建列表数组对象。数组类的构造函数会做所有繁重的任务分配内存并遍历列表(可以是任何实际可迭代)。

      CDEF array.array anorms2_arr = array.array('D',anorms2)


  3. 其数据传递给你的函数:

     返回contr_hrr(..,anorms2_arr.data.as_doubles)


阵列是一个标准Python模块 。用Cython通过增加 arr.data.as_xxx 在上面一些特殊的支持,如缓冲区接口直接访问底层内存块。不幸的是,这种支持只是这里记录
您还可以找到有关最近这次线程
的一些细节。

I'm writting a Cython wrapper to a C function. I have a pxd file with the following signature:

double contr_hrr(int lena, double xa, double ya, double za, double *anorms)

When I try to call this from a pyx file

...
return contr_hrr(len(acoefs),a.origin[0],a.origin[1],a.origin[2],anorms2)

where anorms2 is a python list, I get the error message:

cython/ctwo.pyx:35:80: Cannot convert Python object to 'double *'

How do I pass a python list to a C function as a double array?

解决方案

  1. cimport array:

    from cpython cimport array
    

  2. Create an array object from your list. array class constructor will do all the heavy lifting allocating memory and iterating over your list (could be any iterable actually).

    cdef array.array anorms2_arr = array.array('d', anorms2)
    

  3. Pass its data to your function:

    return contr_hrr(.., anorms2_arr.data.as_doubles)
    

array is a standard Python module. Cython adds some special support on top, like buffer interface and direct access to the underlying memory block via arr.data.as_xxx. Unfortunately, this support is only documented here. You can also find some details about array usage in this recent thread.

这篇关于用Cython:不能Python对象转换为“双*'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆