python - 如何使用 ctypes 从 Python3 访问 C 中的某些常量值

标签 python linux ctypes

如何使用 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/

相关文章:

python - 在 Python 中接收 WM_COPYDATA

python - 在 Win32 上将临时 DLL 加载到 Python

python - 对于每个 IP 循环

python - Hackerrank Quest——错误还是误解?

python - Google App Engine 中的邮件收发(reply_to 字段)

linux - 在 ELF 二进制文件中导入名称

python - 数据在 c 和 python 之间损坏

python - Pyodbc - 使用 WHERE 子句运行 SQL 查询(语法错误)

php - 为什么 "500 internal server error"具有 index.php 权限 666?

java - 为 Postgres 安装 JDBC 时遇到问题