python-c-api - 如何从python的C文件中引用#defines?

标签 python-c-api python-c-extension

我有一个C文件,其中有一堆#defines,我想从python引用这些位。它们足够多,我不想将它们复制到我的python代码中,而是有一种可以接受的直接从python中引用它们的方法吗?

注意:我知道我可以打开头文件并解析它,这很简单,但是如果有更多的Python方式,我想使用它。

编辑:

这些是非常简单的#define,用于定义掩码中位的含义,例如:

#define FOO_A 0x3
#define FOO_B 0x5

最佳答案

在假设C .h文件仅包含#defines(因此没有外部链接可用于该文件)的情况下运行,则以下代码可与swig 2.0(http://www.swig.org/)和python 2.7一起使用)。假设包含刚刚定义的文件被命名为just_defines.h,如上所述:

#define FOO_A 0x3
#define FOO_B 0x5

然后:
swig -python -module just just_defines.h ## generates just_defines.py and just_defines_wrap.c
gcc -c -fpic just_defines_wrap.c -I/usr/include/python2.7 -I. ## creates just_defines_wrap.o
gcc -shared just_defines_wrap.o -o _just.so ## create _just.so, goes with just_defines.py

用法:
$ python 
Python 2.7.3 (default, Aug  1 2012, 05:16:07) 
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import just
>>> dir(just)
['FOO_A', 'FOO_B', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '_just', '_newclass', '_object', '_swig_getattr', '_swig_property', '_swig_repr', '_swig_setattr', '_swig_setattr_nondynamic']
>>> just.FOO_A
3
>>> just.FOO_B
5
>>> 

如果.h文件还包含入口点,则需要链接到某个库(或更多库)以解析这些入口点。这使解决方案更加复杂,因为您可能必须寻找正确的库。但是对于“确定情况”,您不必为此担心。

关于python-c-api - 如何从python的C文件中引用#defines?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12147394/

相关文章:

python - python中实例变量和属性之间的区别?

python - 在 python 中导入时重定向 C 函数的标准输出时出现问题

python - c-extension 中 python 日志记录模块的使用

python - 对于 Python C 扩展,使用 Py_DECREF 而不是 Py_XDECREF 有什么好处吗?

python - Python 3 中的 PyClass_New 等价物是什么?

python - 如何使用 pybind11 从 C++ 调用 python 函数?

python - 如何在 C(++) 中(反)序列化 PyObject*?

python - 实现 nb_inplace_add 会导致返回只读缓冲区对象

python - 从 C 返回 CTypes 指针

python - 从 python 绑定(bind)到 pgcrypto