我想做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模块中的an属性。还有其他选择吗?
发布于 2011-04-19 00:20:58
这里有一种方法,虽然看似繁琐,但对于任何给定的.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
>>>
发布于 2019-11-27 02:35:19
它在我的案例中起作用了。也许对某些人也有帮助:
在我的例子中,我需要从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)
我希望这能像对我一样对某人有帮助=)
发布于 2022-01-07 10:20:30
示例标题:
// myheader.hh
#ifndef MYHEADER
#define MYHEADER
#define NONE 0
#endif
根据我的经验,对于类似的情况,如果没有const
关键字,就会创建一个变量,并且它在#define
中不是常量。我在Cython生成的C++文件的末尾发现了一些对宏的赋值,这是不允许赋值给NONE
的。
cdef extern from "myheader.hh":
int NONE
这是一个真实的常量:
cdef extern from "myheader.hh":
const int NONE
没有const
关键字的Cython中的错误:https://github.com/cython/cython/issues/2621
https://stackoverflow.com/questions/5697479
复制相似问题