examples/natmod: Add urandom native module example.

pull/1/head
Damien George 2019-12-13 13:30:44 +11:00
parent 48e9262f55
commit ba84453f77
4 changed files with 52 additions and 0 deletions

View File

@ -0,0 +1,13 @@
# Location of top-level MicroPython directory
MPY_DIR = ../../..
# Name of module (different to built-in urandom so it can coexist)
MOD = urandom_$(ARCH)
# Source files (.c or .py)
SRC = urandom.c
# Architecture to build for (x86, x64, armv7m, xtensa, xtensawin)
ARCH = x64
include $(MPY_DIR)/py/dynruntime.mk

View File

@ -0,0 +1,34 @@
#define MICROPY_ENABLE_DYNRUNTIME (1)
#define MICROPY_PY_URANDOM (1)
#define MICROPY_PY_URANDOM_EXTRA_FUNCS (1)
#include "py/dynruntime.h"
// Dynamic native modules don't support a data section so these must go in the BSS
uint32_t yasmarang_pad, yasmarang_n, yasmarang_d;
uint8_t yasmarang_dat;
#include "extmod/modurandom.c"
mp_obj_t mpy_init(mp_obj_fun_bc_t *self, size_t n_args, size_t n_kw, mp_obj_t *args) {
MP_DYNRUNTIME_INIT_ENTRY
yasmarang_pad = 0xeda4baba;
yasmarang_n = 69;
yasmarang_d = 233;
mp_store_global(MP_QSTR___name__, MP_OBJ_NEW_QSTR(MP_QSTR_urandom));
mp_store_global(MP_QSTR_getrandbits, MP_OBJ_FROM_PTR(&mod_urandom_getrandbits_obj));
mp_store_global(MP_QSTR_seed, MP_OBJ_FROM_PTR(&mod_urandom_seed_obj));
#if MICROPY_PY_URANDOM_EXTRA_FUNCS
mp_store_global(MP_QSTR_randrange, MP_OBJ_FROM_PTR(&mod_urandom_randrange_obj));
mp_store_global(MP_QSTR_randint, MP_OBJ_FROM_PTR(&mod_urandom_randint_obj));
mp_store_global(MP_QSTR_choice, MP_OBJ_FROM_PTR(&mod_urandom_choice_obj));
#if MICROPY_PY_BUILTINS_FLOAT
mp_store_global(MP_QSTR_random, MP_OBJ_FROM_PTR(&mod_urandom_random_obj));
mp_store_global(MP_QSTR_uniform, MP_OBJ_FROM_PTR(&mod_urandom_uniform_obj));
#endif
#endif
MP_DYNRUNTIME_INIT_EXIT
}

View File

@ -36,8 +36,10 @@
// http://www.literatecode.com/yasmarang
// Public Domain
#if !MICROPY_ENABLE_DYNRUNTIME
STATIC uint32_t yasmarang_pad = 0xeda4baba, yasmarang_n = 69, yasmarang_d = 233;
STATIC uint8_t yasmarang_dat = 0;
#endif
STATIC uint32_t yasmarang(void)
{
@ -208,6 +210,7 @@ STATIC mp_obj_t mod_urandom___init__() {
STATIC MP_DEFINE_CONST_FUN_OBJ_0(mod_urandom___init___obj, mod_urandom___init__);
#endif
#if !MICROPY_ENABLE_DYNRUNTIME
STATIC const mp_rom_map_elem_t mp_module_urandom_globals_table[] = {
{ MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_urandom) },
#ifdef MICROPY_PY_URANDOM_SEED_INIT_FUNC
@ -232,5 +235,6 @@ const mp_obj_module_t mp_module_urandom = {
.base = { &mp_type_module },
.globals = (mp_obj_dict_t*)&mp_module_urandom_globals,
};
#endif
#endif //MICROPY_PY_URANDOM

View File

@ -23,6 +23,7 @@ TEST_MAPPINGS = {
'btree': 'btree/btree_$(ARCH).mpy',
'framebuf': 'framebuf/framebuf_$(ARCH).mpy',
'uheapq': 'uheapq/uheapq_$(ARCH).mpy',
'urandom': 'urandom/urandom_$(ARCH).mpy',
'ure': 'ure/ure_$(ARCH).mpy',
'uzlib': 'uzlib/uzlib_$(ARCH).mpy',
}