gpt4 book ai didi

python - 在 Python 中使用 ctypes.util.find_library 获取库的完整路径

转载 作者:太空狗 更新时间:2023-10-29 11:09:12 27 4
gpt4 key购买 nike

在 Python 中,ctypes.util.find_library 可用于以类似于编译器的方式定位库。在 Mac OSX 中,该函数返回完整路径名。但是在 linux 中,只返回文件名。 (这里是 docs )

有没有办法在 linux 中也获得完整路径?

最佳答案

您可以加载库并使用 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
$

关于python - 在 Python 中使用 ctypes.util.find_library 获取库的完整路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22579308/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com