Cython 在什么情况下将结构体转换为字典?
In what circumstances does Cython convert structs to dictionaries?
我在很多地方(包括 )读到过 cython 可以将结构转换为字典,但我似乎无法在文档中找到它。这真的发生了吗?如果是这样,这是在什么情况下发生的?
我无法使用以下代码执行此操作:
# pxd:
cdef extern from "main.h":
ctypedef struct something_t:
int a
int b
# pyx:
cdef public void do_stuff(something_t *number):
number.a = 1 # works
number[0].a = 2 # works
number['a'] = 3 # doesn't work: Cannot assign type 'long' to 'something_t'
number[0]['a'] = 4 # doesn't work: Cannot assign type 'long' to 'something_t'
当C结构类型(cdef struct
或ctypedef struct
)的变量被转换为Python object
类型的变量时发生。
cdef something_t s = [1, 2] # declare and initialize C struct
cdef object sobj = s # sobj is assigned {'a': 1, 'b': 2} from s data
只是自动转换而已,仅此而已。您不能像示例中那样将 dict 语法与 C 结构或 C 结构语法与 Python 字典一起使用。
我在很多地方(包括
我无法使用以下代码执行此操作:
# pxd:
cdef extern from "main.h":
ctypedef struct something_t:
int a
int b
# pyx:
cdef public void do_stuff(something_t *number):
number.a = 1 # works
number[0].a = 2 # works
number['a'] = 3 # doesn't work: Cannot assign type 'long' to 'something_t'
number[0]['a'] = 4 # doesn't work: Cannot assign type 'long' to 'something_t'
当C结构类型(cdef struct
或ctypedef struct
)的变量被转换为Python object
类型的变量时发生。
cdef something_t s = [1, 2] # declare and initialize C struct
cdef object sobj = s # sobj is assigned {'a': 1, 'b': 2} from s data
只是自动转换而已,仅此而已。您不能像示例中那样将 dict 语法与 C 结构或 C 结构语法与 Python 字典一起使用。