From 8494ab2f2adfc0d3904f7259641ebc21b1fba218 Mon Sep 17 00:00:00 2001 From: Ihor Dutchak <> Date: Thu, 21 Nov 2024 13:35:06 +0200 Subject: [PATCH] Optimize get_report_descriptor - use HID_API_MAX_REPORT_DESCRIPTOR_SIZE from hidapi.h - avoid dynamic memory allocation (use stack variable) - replace list.append with direct list creation from memory view --- chid.pxd | 2 ++ hid.pyx | 28 ++++++++-------------------- 2 files changed, 10 insertions(+), 20 deletions(-) diff --git a/chid.pxd b/chid.pxd index 523a462..8d3c3ab 100644 --- a/chid.pxd +++ b/chid.pxd @@ -1,6 +1,8 @@ from libc.stddef cimport wchar_t, size_t cdef extern from "": + const int HID_API_MAX_REPORT_DESCRIPTOR_SIZE + ctypedef struct hid_device: pass diff --git a/hid.pyx b/hid.pyx index 38cc040..7c47032 100644 --- a/hid.pyx +++ b/hid.pyx @@ -330,12 +330,8 @@ cdef class device: result = hid_send_feature_report(c_hid, cbuff, c_buff_len) return result - def get_report_descriptor(self, int max_length=4096): - """Return the report descriptor up to max_length bytes. - If max_length is bigger than the actual descriptor, the full descriptor will be returned. - - :param max_length: Maximum number of bytes to read, must be positive - :type max_length: int + def get_report_descriptor(self): + """Return the HID Report Descriptor for this device. :return: :rtype: List[int] @@ -345,22 +341,14 @@ cdef class device: if self._c_hid == NULL: raise ValueError('not open') - cdef unsigned char* cbuff - cdef size_t c_descriptor_length = max(1, max_length) + cdef unsigned char cbuff[HID_API_MAX_REPORT_DESCRIPTOR_SIZE] cdef hid_device * c_hid = self._c_hid cdef int n - result = [] - try: - cbuff = malloc(max_length) - with nogil: - n = hid_get_report_descriptor(c_hid, cbuff, c_descriptor_length) - if n < 0: - raise IOError('read error') - for i in range(n): - result.append(cbuff[i]) - finally: - free(cbuff) - return result + with nogil: + n = hid_get_report_descriptor(c_hid, cbuff, sizeof(cbuff)) + if n < 0: + raise IOError('read error') + return list(cbuff[:n]) def get_feature_report(self, int report_num, int max_length): """Receive feature report.