forcing ctypes.cdll.LoadLibrary() to reload library from file

前端 未结 2 1205
北海茫月
北海茫月 2020-12-20 23:49

I have the following code

import ctypes
lib1 = ctypes.cdll.LoadLibrary(\"./mylib.so\")
# modify mylib.so (code generation and compilation) or even delete it
         


        
2条回答
  •  北海茫月
    2020-12-21 00:25

    Simplifying CristiFatis answer a bit, I wrote a close-library function. The following code can be used to develop in your shared library and call it (in the most recent version) from python.

    import ctypes
    def ctypesCloseLibrary(lib):
        dlclose_func = ctypes.CDLL(None).dlclose
        dlclose_func.argtypes = [ctypes.c_void_p]
        dlclose_func.restype = ctypes.c_int
    
        dlclose_func(lib._handle)
    
    if __name__== "__main__":
        lib = ctypes.cdll.LoadLibrary('./mylib.so')
    
        # do things with lib_MyClass
    
        ctypesCloseLibrary(lib)
    

    Just call ctypesCloseLibrary when you want lib to be reloadable by lib = ctypes.cdll.LoadLibrary('./mylib.so').

提交回复
热议问题