如何在Cython模块中将#defined C值公开给Python? [英] How can a #defined C value be exposed to Python in a Cython module?

查看:65
本文介绍了如何在Cython模块中将#defined C值公开给Python?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想制作此处定义的整数常量(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

可作为我正在使用的Cython定义模块的常规属性,以便Python应用程序代码可以访问它们(将它们传递给根据它们定义的包装API)。

available as normal attributes of a Cython defined module I'm working on, so that Python application code can access them (to pass them in to wrapped APIs which are defined in terms of them).

我已经看过用cdef将它们定义为整数或枚举,但是这些方法均未将值绑定到Cython模块中的一个属性。还有什么其他选择?

I've looked at defining these with cdef as integers or enums, but neither of these approaches actually binds the value to an an attribute in the Cython module. What other options are there?

推荐答案

这是一种方法,虽然看起来很乏味,但可以对任何给定的.h进行自动化。文件作为输入:

Here's one way, which, while seemingly tedious, could feasibly be automated for any given .h file as input:

步骤1。将所需的所有常量输入文件,例如 bulletdefs.h ,其中具有 #defines 但带有下划线的前导字符,例如:

Step 1. Get all the constants you want into a file, say bulletdefs.h, which has the #defines but with leading underscores, e.g:

#define _ACTIVE_TAG 1
#define _ISLAND_SLEEPING 2
#define _WANTS_DEACTIVATION 3
#define _DISABLE_DEACTIVATION 4
#define _DISABLE_SIMULATION 5

步骤2。在模块的pyx文件中插入一个部分,例如 bullet.pyx

Step 2. Insert a section into the pyx file for your module, say 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

然后,当您编译模块,应该会达到预期的效果:

Then, when you compile your module, you should get the intended effect:

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
>>>

这篇关于如何在Cython模块中将#defined C值公开给Python?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆