问题描述
我正在使用Cython包装C库。 C库的头文件定义了许多常量,因此在我的cython模块中,我有类似以下内容:
I'm using Cython to wrap a C library. The C library's header file defines a number of constants, so in my cython module, I have something like:
cdef extern from "lib.h":
cdef int CONST_A = 0
cdef int CONST_B = 1
编译扩展名时,常量在Python中不可用。我试图做这样的事情,但是似乎没有用:
When I compile the extension, the constants are not available in Python. I tried doing something like this, but it did not seem to work:
cdef extern from "lib.h":
cdef int CONST_A = 0
cdef int CONST_B = 1
CONST_A = CONST_A
CONST_B = CONST_B
关于如何使这些常量在Python中可用的任何想法?
Any ideas on how to make these constants available in Python?
推荐答案
您说得对,因为Cython似乎有一个洞。
You're right in that there seems to be a hole in Cython there.
我可以声明 cpdef int CONST_C = 3
并且可以编译,但在Python中不可见。这似乎是一个错误-如果它接受语法,则应该对其进行合理的处理。
I can declare cpdef int CONST_C = 3
and it compiles but isn't visible from Python. That would seem to be a bug -- if it accepts the syntax, it should do something reasonable with it.
似乎起作用的一件事是:
One thing that did seem to work is this:
cpdef enum:
CONST_A = 0
CONST_B = 1
这可能对您的情况足够好,但似乎在许多用例中都可以很好地工作-也许这就是为什么该bug并非如此没注意到吗?
That may or may not be good enough for your case, but it seems it would work well for many use-cases -- maybe it's why the bug wasn't noticed?
这篇关于使用Cython从标头导出常量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!