|
| 1 | +/* This example demonstrates the following features in a native module: |
| 2 | + - defining a simple function exposed to Python |
| 3 | + - defining a local, helper C function |
| 4 | + - getting and creating integer objects |
| 5 | +*/ |
| 6 | + |
| 7 | +// Include the header file to get access to the MicroPython API |
| 8 | +#include "py/dynruntime.h" |
| 9 | + |
| 10 | +// Helper function to compute factorial |
| 11 | +STATIC mp_int_t factorial_helper(mp_int_t x) { |
| 12 | + if (x == 0) { |
| 13 | + return 1; |
| 14 | + } |
| 15 | + return x * factorial_helper(x - 1); |
| 16 | +} |
| 17 | + |
| 18 | +// This is the function which will be called from Python, as factorial(x) |
| 19 | +STATIC mp_obj_t factorial(mp_obj_t x_obj) { |
| 20 | + // Extract the integer from the MicroPython input object |
| 21 | + mp_int_t x = mp_obj_get_int(x_obj); |
| 22 | + // Calculate the factorial |
| 23 | + mp_int_t result = factorial_helper(x); |
| 24 | + // Convert the result to a MicroPython integer object and return it |
| 25 | + return mp_obj_new_int(result); |
| 26 | +} |
| 27 | +// Define a Python reference to the function above |
| 28 | +STATIC MP_DEFINE_CONST_FUN_OBJ_1(factorial_obj, factorial); |
| 29 | + |
| 30 | +// This is the entry point and is called when the module is imported |
| 31 | +mp_obj_t mpy_init(mp_obj_fun_bc_t *self, size_t n_args, size_t n_kw, mp_obj_t *args) { |
| 32 | + // This must be first, it sets up the globals dict and other things |
| 33 | + MP_DYNRUNTIME_INIT_ENTRY |
| 34 | + |
| 35 | + // Make the function available in the module's namespace |
| 36 | + mp_store_global(MP_QSTR_factorial, MP_OBJ_FROM_PTR(&factorial_obj)); |
| 37 | + |
| 38 | + // This must be last, it restores the globals dict |
| 39 | + MP_DYNRUNTIME_INIT_EXIT |
| 40 | +} |
0 commit comments