|
| 1 | +// Include MicroPython API. |
| 2 | +#include "py/runtime.h" |
| 3 | + |
| 4 | +// This is the function which will be called from Python as cexample.add_ints(a, b). |
| 5 | +STATIC mp_obj_t example_add_ints(mp_obj_t a_obj, mp_obj_t b_obj) { |
| 6 | + // Extract the ints from the micropython input objects. |
| 7 | + int a = mp_obj_get_int(a_obj); |
| 8 | + int b = mp_obj_get_int(b_obj); |
| 9 | + |
| 10 | + // Calculate the addition and convert to MicroPython object. |
| 11 | + return mp_obj_new_int(a + b); |
| 12 | +} |
| 13 | +// Define a Python reference to the function above. |
| 14 | +STATIC MP_DEFINE_CONST_FUN_OBJ_2(example_add_ints_obj, example_add_ints); |
| 15 | + |
| 16 | +// Define all properties of the module. |
| 17 | +// Table entries are key/value pairs of the attribute name (a string) |
| 18 | +// and the MicroPython object reference. |
| 19 | +// All identifiers and strings are written as MP_QSTR_xxx and will be |
| 20 | +// optimized to word-sized integers by the build system (interned strings). |
| 21 | +STATIC const mp_rom_map_elem_t example_module_globals_table[] = { |
| 22 | + { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_cexample) }, |
| 23 | + { MP_ROM_QSTR(MP_QSTR_add_ints), MP_ROM_PTR(&example_add_ints_obj) }, |
| 24 | +}; |
| 25 | +STATIC MP_DEFINE_CONST_DICT(example_module_globals, example_module_globals_table); |
| 26 | + |
| 27 | +// Define module object. |
| 28 | +const mp_obj_module_t example_user_cmodule = { |
| 29 | + .base = { &mp_type_module }, |
| 30 | + .globals = (mp_obj_dict_t *)&example_module_globals, |
| 31 | +}; |
| 32 | + |
| 33 | +// Register the module to make it available in Python. |
| 34 | +MP_REGISTER_MODULE(MP_QSTR_cexample, example_user_cmodule, MODULE_CEXAMPLE_ENABLED); |
0 commit comments