如何使用 ctypes 从 python 访问预定义的常量值?
我尝试使用 ctypes 获取一个值,例如 SIGTERM(很明显,在我的环境 x64 linux 中该值是 15。)
以下是我编写的代码,但它引发了 ValueError ( undefined symbol )。
为什么会出现这个错误?
请注意,我使用 Ubuntu 19.10、x64、Python 3.7.5
代码:
from ctypes import *
from ctypes.util import *
libc_path = find_library("c")
libc = CDLL(libc_path)
sigterm_value = c_int.in_dll(libc, "SIGTERM")
最佳答案
这是因为 SIGTERM ( [man7]: SIGNAL(7) ) 是一个 宏 (#define
: [GNU.GCC]: Object-like Macros ) 而不是常量。
因此,它并不驻留在libc中(这意味着您无法通过CTypes获取它),但是它只是一个别名(如果您愿意的话),在编译之前被预处理器替换为(C)源代码中的值。
根据(官方)源文件([SourceWare]: [glibc.git]/bits/signum-generic.h):
#define SIGTERM 15 /* Termination request. */
在 Ubtu 16 64 位 中(我知道它很旧,但它是此时唯一运行的 Nix VM),它最终成为定义于/usr/include/bits/signum.h:
#define SIGTERM 15 /* Termination (ANSI). */
您应该使用[Python 3.Docs]: signal - Set handlers for asynchronous events :
>>> import signal >>> signal.SIGTERM <Signals.SIGTERM: 15> >>> signal.SIGTERM.value 15
关于python - 如何使用 ctypes 从 Python3 访问 C 中的某些常量值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59517431/