Python scripts


Python scripts can utilise the UPDD API using the ctypes library. To that end, we've provided upddapi.py, which provides definitions for the UPDD API's important constants, structures (such as _PointerEvent) and functions, as well as a few convenience functions to help common use cases.

Generally, the UPDD API works the same in Python as it does in C or C++. There are a few Python specific caveats regarding callback functions, such as those passed to TBApiRegisterEvent:

  1. Callback functions will be executed in a dedicated thread managed by the UPDD API. We recommend using Python's threading or asynchronous libraries to process events in a Python-controlled thread.
  2. Be aware that pointers to a C structure passed to callback functions are not guaranteed to remain valid after the callback function finishes executing. It's best to make your own copy of that structure for further processing, since it will remain valid as long as Python has a reference to it.

upddapi.py provides two convenience functions to help mitigate the above issues:

create_event_callback: This returns a ctypes callback that can be passed to TBApiRegisterEvent. It takes as its only argument a Python function with two parameters: the event type, and the event itself. This automatically handles copying the pointer provided by the UPDD API into a _PointerEvent ctypes structure whose memory is managed by Python normally.

create_event_callback_async: This is the same as create_event_callback, but instead you pass it an asynchronous function, for scripts that use Python's asyncio library. It has one optional keyword argument event_loop, which specifies the event loop that the asynchronous function will be called in. If it's not provided, then the current event loop is used.

Here is a simple script demonstrating the use of upddapi.py with Python's asyncio library to process digitiser events safely in Python's main thread.

Search