From Array of Structs?

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]

The previous memoryview casting compiles but when run gives a:

  ValueError: Expected 1 dimension(s), got 1

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.


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

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

链接地址: http://www.djcxy.com/p/14278.html

上一篇: 在Google跟踪代码管理器中跟踪Google Analytics的本地主机

下一篇: 从数组结构?