我尝试创建一个用于定义ctypes.Structure的宏。宏如下所示:
(defmacro struct [name fields]
`(defclass ~name [ctypes.Structure]
[-fields-
~(lfor i (range 0 (len fields) 2)
(tuple [
(str (get fields (+ i 1)))
(get fields i)))]))
我认为lfor表达式将生成一个元组列表,但是,当我使用macroexpand扩展宏时,我发现生成的列表是一个列表列表,没有创建任何元组。宏展开的结果由下式给出:
=> (macroexpand '(struct Point [ctypes.c_int x ctypes.c_int y]))
HyExpression([
HySymbol('defclass'),
HySymbol('Point'),
HyList([
HySymbol('ctypes.Structure')]),
HyList([
HySymbol('-fields-'),
HyList([
HyList([
HyString('x'),
HySymbol('ctypes.c_int')]),
HyList([
HyString('y'),
HySymbol('ctypes.c_int')])])])])
我很困惑lfor表达式中的元组似乎根本不起作用。
答案 0 :(得分:0)
由于我是混合新手,因此我不熟悉宏机制。经过几次尝试,终于使它正常工作,如下所示:
(defmacro compound [typename name fields]
`(defclass ~name [~typename]
[-fields-
~(lfor i (range 0 (len fields) 2)
`(,
~(str (get fields (+ i 1)))
~(get fields i)))]))