加载的dll的路径是什么?

now*_*wox 5 python dll ctypes dllimport

我在 Cygwin 下加载了一个dllwithctypes以下内容:

import ctypes
ctypes.cdll.LoadLibrary('foo.dll')
Run Code Online (Sandbox Code Playgroud)

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

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

subprocess.Popen(["which", lib], stdout=subprocess.PIPE).stdout.read().strip()
Run Code Online (Sandbox Code Playgroud)

Ery*_*Sun 3

在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)
Run Code Online (Sandbox Code Playgroud)

输出:

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)
Run Code Online (Sandbox Code Playgroud)