用Cython Memoryviews - 从结构的数组? [英] Cython Memoryviews -- From Array of Structs?

查看:160
本文介绍了用Cython Memoryviews - 从结构的数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想赶紧用尽可能少的副本结构可能很长数组,我逐渐从C接收填写。

I'd like to quickly fill with as few copies as possible a long array of structs that I'm receiving incrementally from C.

如果我的结构是只有小学数据类型,如下所示:

If my struct is only primary data types, like the following:

cdef packed struct oh_hi:
    int lucky
    char unlucky

然后执行以下正常工作:

Then the following works fine:

  DEF MAXPOWER = 1000000
  cdef oh_hi * hi2u = <oh_hi *>malloc(sizeof(oh_hi)*MAXPOWER)
  cdef oh_hi [:] hi2me = <oh_hi[:MAXPOWER]> hi2u

但是,一旦我改变我的结构持有一个字符数组:

But once I change my struct to hold a character array:

cdef packed struct oh_hi:
    int lucky
    char unlucky[10]

在previous memoryview铸造编译但在运行时给出了:

The previous memoryview casting compiles but when run gives a:

  ValueError: Expected 1 dimension(s), got 1

有没有一种简单的方法在用Cython做到这一点?我知道,我可以创建一个结构化的阵列,但据我所知,这不会让我分配C的结构直入它。

Is there an easy way to do this in Cython? I'm aware that I could create a structured array, but afaik, that wouldn't let me assign the C structs straight into it.

推荐答案

其实,只是建立一个结构化numpy的数组,然后一个memoryview工作得很好。

Actually, just building a structured numpy array and then a memoryview works just fine.

cdef np.ndarray hi2u = np.ndarray((MAXPOWER,),dtype=[('lucky','i4'),('unlucky','a10')])
cdef oh_hi [:] hi2me = hi2u

此的表现似乎相当不错,如果你需要把数据传回在Python这样可以节省以后的副本。按照往常一样,numpy的版本是pretty不错。 = P

The performance of this seems quite good and this saves a later copy if you need the data back in python. As per usual, the numpy version is pretty good. =p

这篇关于用Cython Memoryviews - 从结构的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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