在Python中使用ctypes.util.find_library获取库的完整路径
作者:互联网
在Python中,可以使用ctypes.util.find_library以类似于编译器的方式来定位库.在Mac OSX中,该函数返回完整路径名.但是在Linux中,仅返回文件名. (这里是docs)
有没有办法在Linux中也获得fullpath?
解决方法:
您可以加载库,并使用dl_iterate_phdr
遍历加载的库:
#!python
from ctypes import *
from ctypes.util import find_library
# this struct will be passed as a ponter,
# so we don't have to worry about the right layout
class dl_phdr_info(Structure):
_fields_ = [
('padding0', c_void_p), # ignore it
('dlpi_name', c_char_p),
# ignore the reset
]
# call back function, I changed c_void_p to c_char_p
callback_t = CFUNCTYPE(c_int,
POINTER(dl_phdr_info),
POINTER(c_size_t), c_char_p)
dl_iterate_phdr = CDLL('libc.so.6').dl_iterate_phdr
# I changed c_void_p to c_char_p
dl_iterate_phdr.argtypes = [callback_t, c_char_p]
dl_iterate_phdr.restype = c_int
def callback(info, size, data):
# simple search
if data in info.contents.dlpi_name:
print(info.contents.dlpi_name)
return 0
if __name__ == '__main__':
# the target lib we want to find
target_lib = find_library('xml2')
print(target_lib)
# load it
lib = CDLL(target_lib)
# iterate over the loaded libs
dl_iterate_phdr(callback_t(callback), target_lib)
例如:
$python test.py
libxml2.so.2
/usr/lib/libxml2.so.2
$
标签:ctypes,shared-libraries,linux,python,macos 来源: https://codeday.me/bug/20191121/2055750.html