加载的dll的路径是什么?

What is the path of the loaded dll?

我在 Cygwin 下使用 ctypes 加载 dll,其中包含以下内容:

import ctypes
ctypes.cdll.LoadLibrary('foo.dll')

如何获得我的dll的绝对路径?

问题是我完全不知道 dll 的位置。我可以联系以下内容来获取此信息吗?

subprocess.Popen(["which", lib], stdout=subprocess.PIPE).stdout.read().strip()

在Unix中,加载共享库的路径可以通过调用dladdr库中符号的地址来确定,例如函数。

示例:

import ctypes
import ctypes.util

libdl = ctypes.CDLL(ctypes.util.find_library('dl'))

class Dl_info(ctypes.Structure):
    _fields_ = (('dli_fname', ctypes.c_char_p),
                ('dli_fbase', ctypes.c_void_p),
                ('dli_sname', ctypes.c_char_p),
                ('dli_saddr', ctypes.c_void_p))

libdl.dladdr.argtypes = (ctypes.c_void_p, ctypes.POINTER(Dl_info))

if __name__ == '__main__':
    import sys

    info = Dl_info()
    result = libdl.dladdr(libdl.dladdr, ctypes.byref(info))

    if result and info.dli_fname:
        libdl_path = info.dli_fname.decode(sys.getfilesystemencoding())
    else:
        libdl_path = u'Not Found'

    print(u'libdl path: %s' % libdl_path)

输出:

libdl path: /lib/x86_64-linux-gnu/libdl.so.2

如果您在 Windows 并且不需要编程解决方案,例如如果您正在调试某些东西,您可以使用 Process Explorer 查看 python.exe 加载了哪些 DLL。