Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does ctypes.cdll.LoadLibrary(None) work?

How does ctypes.cdll.LoadLibrary() call work with None passed in as an argument? When I try the code below, it seems that the math library gets loaded automatically:

>>> import ctypes
>>> lib = ctypes.cdll.LoadLibrary(None)
>>> lib.sin
<_FuncPtr object at 0x7f36dd65f430>
>>> lib.exp
<_FuncPtr object at 0x7f36dd65f4f8>
>>> 

How does the math library get loaded without being explicitly specified? Do all shared libraries in the standard library get loaded? There is something happening behind the scenes that I don't understand.

like image 233
debashish Avatar asked Apr 17 '18 13:04

debashish


People also ask

What does ctypes CDLL do?

ctypes is a foreign function library for Python. It provides C compatible data types, and allows calling functions in DLLs or shared libraries. It can be used to wrap these libraries in pure Python.

Does ctypes work with C++?

ctypes is the de facto standard library for interfacing with C/C++ from CPython, and it provides not only full access to the native C interface of most major operating systems (e.g., kernel32 on Windows, or libc on *nix), but also provides support for loading and interfacing with dynamic libraries, such as DLLs or ...

What is C_char_p?

c_char_p is a subclass of _SimpleCData , with _type_ == 'z' . The __init__ method calls the type's setfunc , which for simple type 'z' is z_set . In Python 2, the z_set function (2.7.


1 Answers

Note: You encountered this on Nix (on Win it isn't reproducible).

Take a look at [SO]: How to check whether a file exists without exceptions? (@CristiFati's answer).
There, in the last part (the Notes section) of item #4, I explained this exact scenario, quoting the following passage from [man7]: DLOPEN(3):

If filename is NULL, then the returned handle is for the main program. When given to dlsym(), this handle causes a search for a symbol in the main program, followed by all shared objects loaded at program startup, and then all shared objects loaded by dlopen() with the flag RTLD_GLOBAL.

which is used when loading libraries, according to [Python 3]: Loading shared libraries:

All these classes can be instantiated by calling them with at least one argument, the pathname of the shared library. If you have an existing handle to an already loaded shared library, it can be passed as the handle named parameter, otherwise the underlying platforms dlopen or LoadLibrary function is used to load the library into the process, and to get a handle to it.

like image 67
CristiFati Avatar answered Sep 28 '22 15:09

CristiFati