Tom*_*Tom 35 python dll ctypes shared-libraries
有没有办法知道从dllpython外部函数库导出哪些函数ctypes?
如果可能的话,通过c了解有关导出函数的详细信息types.
如果是,有人可以提供一小段代码吗?
Mar*_*ark 15
我不认为ctypes提供此功能.在Windows上使用visual studio:
DUMPBIN -EXPORTS XXX.DLL
Run Code Online (Sandbox Code Playgroud)
或者对于Windows上的mingw:
objdump -p XXX.dll
Run Code Online (Sandbox Code Playgroud)
以下方法适用于 Windows 和 Ubuntu。对于 Windows,需要Cygwin。
假设,有一个c类似下面的文件,名称为test.c.
int func1(int a, int b){
return a + b;
}
int func2(int a, int b){
return a - b;
}
Run Code Online (Sandbox Code Playgroud)
并且test.dll使用以下命令将上述 c 代码编译为文件:
gcc -shared -Wl,-soname,adder -o test.dll -fPIC test.c
Run Code Online (Sandbox Code Playgroud)
下面的 Python 脚本查找 Pythontest.dll可以使用的函数。
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from subprocess import Popen, PIPE
out = Popen(
args="nm ./test.dll",
shell=True,
stdout=PIPE
).communicate()[0].decode("utf-8")
attrs = [
i.split(" ")[-1].replace("\r", "")
for i in out.split("\n") if " T " in i
]
from ctypes import CDLL
functions = [i for i in attrs if hasattr(CDLL("./test.dll"), i)]
print(functions)
Run Code Online (Sandbox Code Playgroud)
我在 Windows 中得到的输出如下:
['func1', 'func2']
Run Code Online (Sandbox Code Playgroud)
我在 Ubuntu 中得到的输出如下:
['_fini', 'func1', 'func2', '_init']
Run Code Online (Sandbox Code Playgroud)
上面列表的项目是_FuncPtr类的对象。
@Mark的答案使用Visual Studio工具.
在Windows上,您还可以使用Dependency Walker获取dll导出的函数名称.
有时名称被破坏,不能用作有效的python函数名.
您可以使用getattr获取损坏函数的句柄,例如:
mylib = ctypes.cdll('mylib.dll')
my_func = getattr(mylib, '_my_func@0')
my_func()
Run Code Online (Sandbox Code Playgroud)