Skip to content

Commit a3df152

Browse files
committed
examples/natmod: Add very simple features0 example to compute factorial.
1 parent b3b9b11 commit a3df152

File tree

2 files changed

+54
-0
lines changed

2 files changed

+54
-0
lines changed

examples/natmod/features0/Makefile

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
# Location of top-level MicroPython directory
2+
MPY_DIR = ../../..
3+
4+
# Name of module
5+
MOD = features0
6+
7+
# Source files (.c or .py)
8+
SRC = features0.c
9+
10+
# Architecture to build for (x86, x64, armv7m, xtensa, xtensawin)
11+
ARCH = x64
12+
13+
# Include to get the rules for compiling and linking the module
14+
include $(MPY_DIR)/py/dynruntime.mk

examples/natmod/features0/features0.c

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
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

Comments
 (0)