Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the path of the loaded dll?

I am loading a dll with ctypes under Cygwin with the following:

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

How can I get the absolute path of my dll?

The problem is that I have absolutely no clues where the dll is located. Can I relate on the following to get this information?

subprocess.Popen(["which", lib], stdout=subprocess.PIPE).stdout.read().strip()
like image 292
nowox Avatar asked Oct 17 '22 11:10

nowox


1 Answers

In Unix, the path of a loaded shared library can be determined by calling dladdr with the address of a symbol in the library, such as a function.

Example:

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)

Output:

libdl path: /lib/x86_64-linux-gnu/libdl.so.2
like image 110
Eryk Sun Avatar answered Oct 23 '22 10:10

Eryk Sun