C coding examples for MicroPython Functions and Methods

C programming, build, interpreter/VM.
Target audience: MicroPython Developers.
Post Reply
User avatar
Mike Teachman
Posts: 69
Joined: Mon Jun 13, 2016 3:19 pm
Location: Victoria, BC, Canada

C coding examples for MicroPython Functions and Methods

Post by Mike Teachman » Mon Nov 26, 2018 4:53 pm

In the last month I started learning how to port ESP-IDF features into the LoBo ESP32 fork. Part of the learning adventure involved writing a C file that provides examples on how MicroPython functions and class methods map into a C implementation -- with a focus on understanding the many different ways that positional and keyword arguments can be implemented in C. For example, how do you write C code to make a positional argument mandatory, versus optional? Or, how do you write C to raise a python exception when a wrong object type has been passed to a method?

If you are on a similar learning path you might be able to use this work. The file is linked below.

https://github.com/MikeTeachman/MicroPy ... examples.c

This file can be compiled into a build and run by importing the "argex" module. I developed it on the ESP32/Lobo port, but I expect it will work for all uPy ports.

Each example shows:
  • uPy interface to the function or method, showing all possible variants of positional and keyword arguments
  • C implementation
Here is a sample:

Code: Select all

// Method Example 3:
//      variable number of positional arguments, specified by min and max
//      NOTE: for a method call, MIN_NUM_METHOD_ARGS must never be zero
//      class Argex:
//          m_min_max(self, [pos1]):
//      from argex import Argex
//      a = Argex(True, 7)
//      a.m_min_max()
//      a.m_min_max(False)

#define MIN_NUM_METHOD_ARGS (1)  // self
#define MAX_NUM_METHOD_ARGS (2)  // self + one Optional positional argument
STATIC mp_obj_t method_min_max_args(size_t n_args, const mp_obj_t *args) {
    argex_obj_t *self = MP_OBJ_TO_PTR(args[0]);

    // important notes:
    //      'n_args' refers to the count of positional args, and +1 for the class instance self
    printf("n_args = %u\n", n_args);

    if (n_args == 1) {
        // when n_args equals 1 it means that ONLY argument passed is the class instance self
        return mp_obj_new_int(self->var1);
    } else {
        self->var1 = mp_obj_get_int(args[1]);
        return mp_const_none;

Posts: 34
Joined: Sat Oct 27, 2018 5:17 pm

Re: C coding examples for MicroPython Functions and Methods

Post by rpr » Mon Nov 26, 2018 9:49 pm


This is excellent. Appreciate your github repository.

Post Reply