此上下文中的句柄基本上是对内存映射库文件的引用。在
然而,在操作系统功能的帮助下,有一些现有的方法可以实现您想要的。在
窗口:
Windows为此提供了一个名为GetModuleFileName的API。一些用法的例子已经是here。在
linux:
已有一个dlinfo函数用于此目的,请参见here。在
我使用ctypes,这是我针对基于linux的系统的解决方案。到目前为止,我对ctypes一无所知,如果有任何改进的建议,我很感激。在from ctypes import *
from ctypes.util import find_library
#linkmap structure, we only need the second entry
class LINKMAP(Structure):
_fields_ = [
("l_addr", c_void_p),
("l_name", c_char_p)
]
libc = CDLL(find_library('c'))
libdl = CDLL(find_library('dl'))
dlinfo = libdl.dlinfo
dlinfo.argtypes = c_void_p, c_int, c_void_p
dlinfo.restype = c_int
#gets typecasted later, I dont know how to create a ctypes struct pointer instance
lmptr = c_void_p()
#2 equals RTLD_DI_LINKMAP, pass pointer by reference
dlinfo(libc._handle, 2, byref(lmptr))
#typecast to a linkmap pointer and retrieve the name.
abspath = cast(lmptr, POINTER(LINKMAP)).contents.l_name
print(abspath)
本文介绍了一种在Linux系统中利用ctypes库获取当前加载库文件绝对路径的方法,并提供了具体实现代码。
952

被折叠的 条评论
为什么被折叠?



