I was wondering that, if I opened my own dll library compiled from custom c code, like this:
import ctypes
my_lib = ctypes.cdll.LoadLibrary('./my_dll.dll')
my_func = my_lib.my_func
# Stuff I want to do with func()
Do I need to close the my_lib object after use, like a file object? Will doing this make the code cleaner, more efficient, and more "pythonic"?
Thanks!
Generally you shouldn't have to free a shared library. Consider that CPython doesn't provide a means to unload a regular extension module from memory. For example, importing sqlite3 will load the _sqlite3 extension and sqlite3 shared library for the life of the process. Unloading extensions is incompatible with the way CPython uses pointers as object IDs. Accessing a deallocated (and possibly reused) address would be undefined behavior.
If you need to unload or reload a shared library, and are confident that it's safe, the _ctypes extension module has POSIX
dlclose
and WindowsFreeLibrary
, which call the system functions of the same name. Both take the library handle as the single argument. This is the_handle
attribute of aCDLL
instance. If unloading the library fails,OSError
is raised.Both
dlclose
andFreeLibrary
work by decrementing the handle's reference count. The library is unloaded when the count is decremented to 0. The count is initially 1 and gets incremented each time POSIXdlopen
or WindowsLoadLibrary
is called for an already loaded library.POSIX Example
POSIX Python
Windows Example
Windows Python