TAGS :Viewed: 8 - Published at: a few seconds ago

[ ctypes unload dll ]

I am loading a dll with ctypes like this:

lib = cdll.LoadLibrary("someDll.dll");

When I am done with the library, I need to unload it to free resources it uses. I am having problems finding anything in the docs regarding how to do this. I see this rather old post: How can I unload a DLL using ctypes in Python?. I am hoping there is something obvious I have not found and less of a hack.

Answer 1


The only truly effective way I have ever found to do this is to take charge of calling LoadLibrary and FreeLibrary. Like this:

import ctypes

# get the module handle and create a ctypes library object
libHandle = ctypes.windll.kernel32.LoadLibraryA('mydll.dll')
lib = ctypes.WinDLL(None, handle=libHandle)

# do stuff with lib in the usual way
lib.Foo(42, 666)

# clean up by removing reference to the ctypes library object
del lib

# unload the DLL
ctypes.windll.kernel32.FreeLibrary(libHandle)