使用ctypes从共享库映射全局变量 [英] Mapping a global variable from a shared library with ctypes

查看:144
本文介绍了使用ctypes从共享库映射全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用以下方法映射在库 libtorque.so 中声明为全局值的int值 pbs_errno



当前,我可以像这样加载库:

 从ctypes import * 
libtorque = CDLL( libtorque.so)

并成功映射了一堆函数。但是,出于错误检查的目的,其中许多设置了 pbs_errno 变量,因此我也需要访问它。但是,如果尝试访问它,则会得到:

 >> pytorque.libtorque.pbs_errno 
< _FuncPtr对象位于0x9fc690>

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

在主标头中声明为 int pbs_errno; ,在主标题中声明为 extern int pbs_errno;



Objdump将符号显示为:

  00000000001294f8 g DO .bss 0000000000000004基本pbs_errno 


解决方案

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



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



例如

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


I'd like to map an int value pbs_errno declared as a global in the library libtorque.so using ctypes.

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. 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; in the main header and extern int pbs_errno; in the API header files.

Objdump shows the symbol as:

00000000001294f8 g    DO .bss   0000000000000004  Base        pbs_errno

解决方案

There's a section in the ctypes docs about accessing values exported in dlls:

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

e.g.

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

这篇关于使用ctypes从共享库映射全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆