Skip to content

Commit

Permalink
call hid_exit on exit
Browse files Browse the repository at this point in the history
  • Loading branch information
RobertoRoos authored and prusnak committed Mar 3, 2021
1 parent 2353c96 commit b94c8a0
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 1 deletion.
1 change: 1 addition & 0 deletions chid.pxd
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ cdef extern from "hidapi.h":
hid_device* hid_open(unsigned short, unsigned short, const wchar_t*)
hid_device* hid_open_path(char *path)
void hid_close(hid_device *)
int hid_exit()
int hid_write(hid_device* device, unsigned char *data, int length) nogil
int hid_read(hid_device* device, unsigned char* data, int max_length) nogil
int hid_read_timeout(hid_device* device, unsigned char* data, int max_length, int milliseconds) nogil
Expand Down
15 changes: 14 additions & 1 deletion hid.pyx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import sys
import atexit
from chid cimport *
from libc.stddef cimport wchar_t, size_t
from cpython.unicode cimport PyUnicode_FromUnicode

cdef extern from "ctype.h":
int wcslen(wchar_t*)
Expand Down Expand Up @@ -65,6 +65,15 @@ def enumerate(int vendor_id=0, int product_id=0):
hid_free_enumeration(info)
return res

def hidapi_exit():
"""Callback for when the script exits.
This prevents memory leaks in the hidapi C library.
Note that the counterpart, hid_init(), is not called explicitly. It will
be called internally when first needed.
"""
hid_exit()

cdef class device:
"""Device class.
Expand Down Expand Up @@ -371,3 +380,7 @@ cdef class device:
if self._c_hid == NULL:
raise ValueError('not open')
return U(<wchar_t*>hid_error(self._c_hid))


# Set a callback to close the HID library as the script exits
atexit.register(hidapi_exit)

0 comments on commit b94c8a0

Please sign in to comment.