简体   繁体   English

使用 ctypes 从共享库映射全局变量

[英]Mapping a global variable from a shared library with ctypes

I'd like to map an int value pbs_errno declared as a global in the library libtorque.so using ctypes.我想使用 ctypes 映射在库libtorque.so声明为全局的 int 值pbs_errno

Currently I can load the library like so:目前我可以像这样加载库:

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

and have successfully mapped a bunch of the functions.并成功映射了一堆函数。 However, for error checking purposes many of them set the pbs_errno variable so I need access to that as well.但是,出于错误检查的目的,他们中的许多人设置了pbs_errno变量,因此我也需要访问它。 However if I try to access it I get:但是,如果我尝试访问它,我会得到:

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

Of course, it's not a function pointer and attempting to call it results in a seg fault.当然,它不是函数指针,尝试调用它会导致段错误。

It's declared as int pbs_errno;它被声明为int pbs_errno; in the main header and extern int pbs_errno;在主标题和extern int pbs_errno; in the API header files.在 API 头文件中。

Objdump shows the symbol as: Objdump 将符号显示为:

00000000001294f8 g    DO .bss   0000000000000004  Base        pbs_errno

There's a section in the ctypes docs about accessing values exported in dlls: ctypes 文档中有一节关于访问在 dll 中导出的值:

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

eg例如

def pbs_errno():
    return c_int.in_dll(libtorque, "pbs_errno")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM