如何在Cython模块中将#defined C值暴露给Python?

Jea*_*one 25 python cython

我想在这里定义整数常量(ACTIVE_TAG等):

//island management, m_activationState1
#define ACTIVE_TAG 1
#define ISLAND_SLEEPING 2
#define WANTS_DEACTIVATION 3
#define DISABLE_DEACTIVATION 4
#define DISABLE_SIMULATION 5
Run Code Online (Sandbox Code Playgroud)

可用作我正在处理的Cython定义模块的普通属性,以便Python应用程序代码可以访问它们(将它们传递给根据它们定义的包装API).

我已经看过用cdef定义这些作为整数或枚举,但这些方法实际上都没有将值绑定到Cython模块中的属性.还有哪些其他选择?

Vin*_*jip 24

这是一种方式,虽然看似乏味,但可以为任何给定的.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
Run Code Online (Sandbox Code Playgroud)

步骤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
Run Code Online (Sandbox Code Playgroud)

然后,当您编译模块时,您应该获得预期的效果:

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
>>>
Run Code Online (Sandbox Code Playgroud)

  • 谢谢.这是有效的,甚至还有一个可以采取的快捷方式(这是我之前被卡住的地方).我可以直接使用bullet中的定义,并通过像`cdef int _ACTIVE_TAG"ACTIVE_TAG"`这样的方式在Cython命名空间中重命名它们.引号中的名称是Cython在C方面寻找的东西,左边的名称是它的值如何暴露给Python. (20认同)

小智 6

它对我来说有效。也许对某人也有帮助:

#define就我而言,我需要从 Linux 内核库中导出。它对我有用:

# 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
Run Code Online (Sandbox Code Playgroud)

在你的.pyx文件中:

from your_compiled_cython_package cimport CLONE_NEWNS

print(CLONE_NEWNS)
Run Code Online (Sandbox Code Playgroud)

我希望这对某人有帮助,就像对我一样=)