Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ctypes unload dll

Tags:

python

ctypes

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.

like image 219
Doo Dah Avatar asked Oct 29 '12 20:10

Doo Dah


1 Answers

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)

Update:

As of Python 3.8, ctypes.WinDLL() no longer accepts None to indicate that no filename is being passed. Instead, you can workaround this by passing an empty string.

See https://bugs.python.org/issue39243

like image 53
David Heffernan Avatar answered Oct 01 '22 09:10

David Heffernan