Search code examples
pythonusbctypeshid

Accessing the HIDAPI library in python


I am trying to use python to communicate with a generic HID device.

I have read that the HIDAPI library, written in C, beats libusb1.0 for simple and stable cross-platform HID communication. However, no one has ever bothered to show how to call the HIDAPI functions from within a python script, and that is where I am having trouble.

I understand enough ctypes to call really simple C functions like:

int add(int n1, int n2) {
    return n1 + n2;
    }

The trouble is that the HIDAPI functions are more complicated, such as (in the HIDAPI header file):

struct hid_device_info HID_API_EXPORT * HID_API_CALL hid_enumerate(unsigned short vendor_id, unsigned short product_id);

which points to this structure (in the mac branch C file):

struct hid_device_info  HID_API_EXPORT *hid_enumerate(unsigned short vendor_id, unsigned short product_id)
{
...
}

where '...' is a whole lot of OS-level code that ends up returning "a pointer to a linked list of type struct #hid_device, containing information about the HID device"

How would you go about using ctypes, or any other tool, to call a function like this in a python script? I'm hoping that this stackoverflow page will serve as a guide for all the other people that would like to solve the same problem, so please give plenty of detail, thank you.


Solution

  • This is not the exact answers to your question, but may give some new pointers.

    When interacting with complex native libraries, you probably need to write some C code to "bridge the gap" and ctypes alone might not cut it. The bridge code simplifies C structures before passing them down to Python and vice versa, as you might not be able to describe all nifties of native code with ctypes.

    You can write native Python C extension by hand, but this is not recommended.

    There are several "bridge toolkits" or code generators what you can use in this kind of situations. One of the most popular ones is Cython which you allow to write .pyx modules where you can freely mix C and Python code.

    http://cython.org/

    .pyx is then compiled to resulting native C module and the wrapping .py module. You can easily import the latter to your application logic.