我想制作the integer constants (ACTIVE_TAG, etc) defined here:
//island management, m_activationState1
#define ACTIVE_TAG 1
#define ISLAND_SLEEPING 2
#define WANTS_DEACTIVATION 3
#define DISABLE_DEACTIVATION 4
#define DISABLE_SIMULATION 5
可用作我正在处理的Cython定义模块的常规属性,以便Python应用程序代码可以访问它们(将它们传递给根据它们定义的包装API)。
我已经看过用cdef定义这些作为整数或枚举,但这些方法实际上都没有将值绑定到Cython模块中的属性。还有哪些其他选择?
答案 0 :(得分:23)
这是一种方式,虽然看似乏味,但可以根据任何给定的.h文件进行自动化:
步骤1.将所需的所有常量输入到文件中,例如bulletdefs.h
,其中包含#defines
但具有前导下划线,例如:
#define _ACTIVE_TAG 1
#define _ISLAND_SLEEPING 2
#define _WANTS_DEACTIVATION 3
#define _DISABLE_DEACTIVATION 4
#define _DISABLE_SIMULATION 5
步骤2.在模块的pyx文件中插入一个部分,比如bullet.pyx
:
cdef extern from "bulletdefs.h":
cdef int _ACTIVE_TAG
cdef int _ISLAND_SLEEPING
cdef int _WANTS_DEACTIVATION
cdef int _DISABLE_DEACTIVATION
cdef int _DISABLE_SIMULATION
ACTIVE_TAG = _ACTIVE_TAG
ISLAND_SLEEPING = _ISLAND_SLEEPING
WANTS_DEACTIVATION = _WANTS_DEACTIVATION
DISABLE_DEACTIVATION = _DISABLE_DEACTIVATION
DISABLE_SIMULATION = _DISABLE_SIMULATION
然后,当您编译模块时,您应该得到预期的效果:
Python 2.7.1+ (r271:86832, Apr 11 2011, 18:05:24)
[GCC 4.5.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import bullet
>>> bullet.ACTIVE_TAG
1
>>> bullet.DISABLE_SIMULATION
5
>>>
答案 1 :(得分:0)
在我的情况下有效。也许对某人也有帮助:
就我而言,我需要从Linux内核库中导出#define
。它对我有用:
# your_pxd_file.pxd
cdef extern from "sched.h": #here are lots of `#define`'s clauses. something like the link: https://github.com/spotify/linux/blob/master/include/linux/sched.h
cdef enum:
CLONE_NEWNS
在您的.pyx
文件中:
from your_compiled_cython_package cimport CLONE_NEWNS
print(CLONE_NEWNS)
我希望这对像我一样对某人有帮助=)