Setting cdef variables from PyObject properties en masse

已查看 25 次
跳至第一个未读帖子

Serdar Yegulalp

未读,
2016年12月27日 00:27:452016/12/27
收件人 cython-users
I have functions that take in an Python object and set the various properties to typed equivalents, e.g.:

cdef int x = pyobject.x, y=pyobject.y, z=pyobject.z

This is done to allow any future manipulations of the variable to be done as purely in C as possible.

Is there a more efficient way to set a whole slew of these at once, rather than using the construction shown above?

Robert Bradshaw

未读,
2016年12月28日 00:00:122016/12/28
收件人 cython...@googlegroups.com
I might write it in multiple lines to be clearer, e.g. 

cdef int x, y, z
x, y, z = pyobject.x, pyobject.y, pyobject.z

You could alternatively fore pyobject to be a Python object, or write a struct that has the relevant members and write helpers that did the unpacking (and packing if need be), e.g.

cdef struct c_members_struct:
    int x
    int y
    int z

cdef [inline] c_members_struct extract_c_members(pyobject):
    cdef c_members_struct c_members
    c_members.x = pyobject.x
    c_members.y = pyobject.y
    c_members.z = pyobject.z
    return c_members

or, if the attributes happen to align exactly, 

cdef c_members_struct c_members = pyobject.__dict__

You should also look at whether all members need to be in C variables, or only a couple accesses dominate the computation. Profile, profile, profile. 

- Robert



回复全部
回复作者
转发
0 个新帖子