【问题标题】:Mapping a global variable from a shared library with ctypes使用 ctypes 从共享库映射全局变量
【发布时间】:2026-02-27 04:35:01
【问题描述】:

我想使用 ctypes 在库 libtorque.so 中映射一个声明为全局的 int 值 pbs_errno

目前我可以像这样加载库:

from ctypes import *
libtorque = CDLL("libtorque.so")

并且已经成功地映射了一堆函数。但是,出于错误检查的目的,他们中的许多人设置了pbs_errno 变量,所以我也需要访问它。但是,如果我尝试访问它,我会得到:

>>> pytorque.libtorque.pbs_errno
<_FuncPtr object at 0x9fc690>

当然,它不是函数指针,尝试调用它会导致段错误。

在主头文件中声明为int pbs_errno;,在API头文件中声明为extern int pbs_errno;

Objdump 显示符号为:

00000000001294f8 g    DO .bss   0000000000000004  Base        pbs_errno

【问题讨论】:

  • 约翰的回答是正确的。设置 restype 只会改变函数的返回类型,AFAICT。如果我实际上尝试将 pbs_errno 作为函数调用,则会导致段错误。

标签: python ctypes


【解决方案1】:

ctypes 文档中有一节关于访问在 dll 中导出的值:

http://docs.python.org/library/ctypes.html#accessing-values-exported-from-dlls

例如

定义 pbs_errno(): 返回 c_int.in_dll(libtorque,“pbs_errno”)

【讨论】:

  • 谢谢。不知何故,我在使用文档时错过了该部分。这是一本包含大量不同内容的大型手册,易于浏览而不会注意到:/