Is there any way to know which functions are exported from the dll
through python foreign function library ctypes
?
And if possible to know details about the exported functions through ctypes
.
If yes, could someone provide a snippet of code?
Is there any way to know which functions are exported from the dll
through python foreign function library ctypes
?
And if possible to know details about the exported functions through ctypes
.
If yes, could someone provide a snippet of code?
@Mark's answer uses Visual Studio tools.
On windows you can also use Dependency Walker to get the function names of dll exports.
Sometimes names are mangled and can't be used as a valid python function name.
You can use
getattr
to get a handle to mangled functions, e.g:If you are on Linux, there is a handy utility
nm
to list the content of a shared library (there is always a handy utility on Linux, especially for C stuff).Here is the question about it.
You use it with the
-D
flag:nm -D ./libMyLib.so
I don't think ctypes offers this functionality. On Windows with visual studio:
Or for mingw on windows:
In general, this is not possible, because, again in general, dynamically loaded libraries do not carry the meta-information you require. It may be possible to obtain that information in certain special cases through system-specific ways, but
ctypes
itself does not fetch that information. You can record such info viactypes
(see e.g. the restype andargtypes
attributes of function pointers), but only after you have obtained it by different means.YES! there is a very clever native method to do it.
let's say you are using Python ctypes. put something like this in your C code:
1) in your C code:
now put PYEXPORT above the function you want to export:
2) After compiling, go back into Python and open your .c file, and parse it similar to this:
shell input: fn
shell output: 'myfunc'
3) Now here's the clever part: define a new function in a string:
NOW do exec(a3) and it will turn that string into a function that you can use.
4) do the usual:
and there you have a python wrapper for a C script without having to modify ten different things every time something changes.
If you've also got the source for said library, and you're looking for a fully automated all-python way, you could use
pycparser
for the file:
prog.c
compiling with
gcc
gives us the pre-processed c file:
prog-preproc.c
then in python:yields
To dig further you can also get parameter and return types. Uncomment
node.show()
for more information from within the Abstract Syntax Tree (AST)I'll be releasing a library for this soon (I'll try to remember to come back and drop a link)