How can I unload a DLL using ctypes in Python?

前端 未结 5 1464
一整个雨季
一整个雨季 2020-11-29 07:50

I\'m using ctypes to load a DLL in Python. This works great.

Now we\'d like to be able to reload that DLL at runtime.

The straightforward approach would s

5条回答
  •  被撕碎了的回忆
    2020-11-29 07:51

    Piotr's answer helped me, but I did run into one issue on 64-bit Windows:

    Traceback (most recent call last):
    ...
    ctypes.ArgumentError: argument 1: : int too long to convert
    

    Adjusting the argument type of the FreeLibrary call as suggested in this answer solved this for me.

    Thus we arrive at the following complete solution:

    import ctypes, ctypes.windll
    
    def free_library(handle):
        kernel32 = ctypes.WinDLL('kernel32', use_last_error=True)
        kernel32.FreeLibrary.argtypes = [ctypes.wintypes.HMODULE]
        kernel32.FreeLibrary(handle)
    

    Usage:

    lib = ctypes.CDLL("foobar.dll")
    free_library(lib._handle)
    

提交回复
热议问题