I wanted to write a stepper motor class in Python, but needed to write the timer callback routine that calculates the new timer period in C for speed reasons. However, I needed a bound function as the callback. Initially I did this:
Code: Select all
from _helper import c_callback_function
class MyClass:
def __init__(self):
self._cached_callback = self._callback
self._timer = Timer(...)
self._timer.callback(self._cached_callback)
def _callback(self, timer):
c_callback_function(self, timer)
So I added a function written in C to bind an object to a free function, so I could do this:
Code: Select all
from _helper import c_callback_function, bind
class MyClass:
def __init__(self):
self._cached_callback = bind(self, c_callback_function)
self._timer = Timer(...)
self._timer.callback(self._cached_callback)
Code: Select all
/**
* Bind an object to a free function.
* @self: a class instance
* @func: a function
* @return a bound function
*/
STATIC mp_obj_t _helper_bind(mp_obj_t self, mp_obj_t func) {
return mp_obj_new_bound_meth(func, self);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_2(_helper_bind_obj, _helper_bind);