gpt4 book ai didi

Python ctypes : get handle to already-loaded shared libraries

转载 作者:太空宇宙 更新时间:2023-11-03 18:07:41 25 4
gpt4 key购买 nike

给定共享库的短名称(例如 gomp,而不是 libgomp.so 等),Python 中确定该库是否已加载的最佳方法是什么,如果是,则找到其完整路径名,以便 ctypes 句柄可以可以得到吗?

最佳答案

这是迄今为止我能想到的最好的解决方案,但从/proc/<pid>/maps阅读感觉有点老套。并对其内容进行字符串解析。

import re, ctypes, os.path

_WHITESPACE = re.compile('\s+')

def get_loaded_lib_pathname(lib_name):
soname = 'lib%s.so' % (lib_name,)
pid = os.getpid()
with open('/proc/%d/maps' % (pid,)) as f:
for line in f.readlines():
tokens = _WHITESPACE.split(line)
addrs, perms, offset, dev, inode, pathname = tokens[:6]
basename = os.path.basename(pathname)
if basename.startswith(soname):
return pathname
return None

def get_lib_handle(lib_name):
pathname = get_loaded_lib_pathname(lib_name)
if pathname is None:
return None
return ctypes.cdll.LoadLibrary(pathname)

libgomp = get_lib_handle('gomp')

关于Python ctypes : get handle to already-loaded shared libraries,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26529147/

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