Solved: constructing a bound function

C programming, build, interpreter/VM.
Target audience: MicroPython Developers.
Post Reply
nedkonz
Posts: 24
Joined: Thu Aug 05, 2021 9:58 pm

Solved: constructing a bound function

Post by nedkonz » Sat Aug 28, 2021 4:05 pm

I'm posting this because I didn't find a solution despite reading the docs and searching this forum.

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)
This worked, but introduced a second function call that was just taking extra time.

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)
This bind function was very simple:

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);

Post Reply