Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/324.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
获取Python中共享库的绝对路径_Python_C_Dll - Fatal编程技术网

获取Python中共享库的绝对路径

获取Python中共享库的绝对路径,python,c,dll,Python,C,Dll,假设我想在Python中使用libc。这可以很容易地做到 from ctypes import CDLL from ctypes.util import find_library libc_path = find_library('c') libc = CDLL(libc_path) 现在,我知道我可以使用ldconfig获取libc的abspath,但是有没有办法从CDLL对象获取它?它的\u手柄是否可以执行某些操作 更新:好的 我需要重新定义链接映射结构,然后 此上下文中的句柄基本上是对

假设我想在Python中使用libc。这可以很容易地做到

from ctypes import CDLL
from ctypes.util import find_library

libc_path = find_library('c')
libc = CDLL(libc_path)
现在,我知道我可以使用ldconfig获取libc的abspath,但是有没有办法从CDLL对象获取它?它的
\u手柄
是否可以执行某些操作

更新:好的


我需要重新定义
链接映射
结构,然后

此上下文中的句柄基本上是对内存映射库文件的引用

然而,在操作系统功能的帮助下,现有的方法可以实现您想要的功能

窗口: Windows为此提供了一个名为
GetModuleFileName
的API。已经有了一些使用示例

linux: 有一个用于此目的的
dlinfo
功能,请参阅


我使用了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)

更直接的是:lmptr=指针(LINKMAP)(。。。;abspath=lmptr.contents.l_name;
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)