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

Question:

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.

Asked By: debashish

||

Answers:

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

Take a look at [SO]: How do I 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.Docs]: ctypes – 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.

Answered By: CristiFati
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.