Skip to content

Commit f644ea7

Browse files
minkustreemcuee
authored andcommitted
Fix #203: libusb sometimes cleaned up too early. (#227)
Each call to libusb1's get_backend returns a new _LibUSB object. When each _LibUSB object falls out of scope, it calls ends up calling libusb_exit() which deinitializes libusb, even if there are still references in scope. Practically speaking, pyusb seems to assume there's only one context active, so returning the same _LibUSB object on subsequent calls to get_backend should prevent there from being more than one call to libusb_exit() when backend objects go out of scope. This should fix errors where the libusb library was being used after libusb_exit() had been called.
1 parent 53f2f20 commit f644ea7

1 file changed

Lines changed: 5 additions & 2 deletions

File tree

‎usb/backend/libusb1.py‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -256,6 +256,7 @@ def _get_iso_packet_list(transfer):
256256
return list_type.from_address(addressof(transfer.iso_packet_desc))
257257

258258
_lib = None
259+
_lib_object = None
259260

260261
def _load_library(find_library=None):
261262
# Windows backend uses stdcall calling convention
@@ -936,12 +937,14 @@ def __read(self, fn, dev_handle, ep, intf, buff, timeout):
936937
return transferred.value
937938

938939
def get_backend(find_library=None):
939-
global _lib
940+
global _lib, _lib_object
940941
try:
941942
if _lib is None:
942943
_lib = _load_library(find_library=find_library)
943944
_setup_prototypes(_lib)
944-
return _LibUSB(_lib)
945+
if _lib_object is None:
946+
_lib_object = _LibUSB(_lib)
947+
return _lib_object
945948
except usb.libloader.LibraryException:
946949
# exception already logged (if any)
947950
_logger.error('Error loading libusb 1.0 backend', exc_info=False)

0 commit comments

Comments
 (0)