Safely Unload / Reload C++ dll in Python 2.7 (Replace dll with a new version)

Viewed 667

I ask this question in the context of most other questions being 5-10 years old on this topic and given the following

  • Windows 7 OS
  • Several versions of a .pyd compiled dll at different file path locations e.g.
    • /ver1.0/lib/my_dll.pyd
    • /ver1.1/lib/my_dll.pyd
  • my_dll.pyd is imported from a secondary file as from my_dll import *, I am not in control of the method or at liberty to alter

I can successfully switch between two .pyd versions as follows

import sys
sys.path.append(r'\path\to\ver_1.0')
import my_dll                    # imports ver 1.0
print my_dll.release_version()
sys.path.pop(-1)
del sys.modules['my_dll']        # remove module dict ref
from IPython import get_ipython  # just in case you run in iPython
get_ipython().magic('reset -sf') # need to remove history!
del my_dll                       # delete the import object

import _ctypes                   # release the library handle
import ctypes
dll = ctypes.CDLL('my_dll.pyd')
_ctypes.FreeLibrary(dll._handle) # for some reason it needs to be
_ctypes.FreeLibrary(dll._handle) # done twice.

sys.path.append(r'\path\to\ver_1.1')
import my_dll
print my_dll.release_version()

The failures of reload are overcome by reloading the C++ .pyd as per the following output

Version 1.0
Version 1.1

my issue is that then I am left with an extremely flimbsy python ecosystem that will crash at almost any new function call.

Is there a more updated methodology of doing this?

References

0 Answers
Related