Skip to content

Instantly share code, notes, and snippets.

@nickfox-taterli
Created March 16, 2025 07:20
Show Gist options
  • Save nickfox-taterli/d66711fa10d2c3178768d5b029057a7a to your computer and use it in GitHub Desktop.
Save nickfox-taterli/d66711fa10d2c3178768d5b029057a7a to your computer and use it in GitHub Desktop.
MicroPython C模块实现笔记
#include <stdio.h>
#include "py/runtime.h"
#include "py/mphal.h"
STATIC mp_obj_t pytest_test(void)
{
printf("pytest module");
return mp_obj_new_int(0);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_0(pydev_test_obj, pytest_test);
STATIC const mp_rom_map_elem_t pytest_table[] = {
{ MP_ROM_QSTR(MP_QSTR_val), MP_ROM_INT(1)}
};
STATIC MP_DEFINE_CONST_DICT(pytest_table_dict, pytest_table);
//将dict封装成object,可以使用pytest.table.val访问
MP_DEFINE_CONST_OBJ_TYPE(pytest_mp_type,
MP_QSTR_table,
MP_TYPE_FLAG_NONE,
locals_dict, &pytest_table_dict);
STATIC const mp_rom_map_elem_t pytest_module_globals_table[] = {
{ MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_pytest) },
//导入OBJ指针,可以是函数或者对象
//导入函数, 访问为pytest.test()
{ MP_ROM_QSTR(MP_QSTR_test), MP_ROM_PTR(&pydev_test_obj) },
//导入为对象, 可通过pytest.table访问
{ MP_ROM_QSTR(MP_QSTR_table), MP_ROM_PTR(&pytest_mp_type) },
//定义int类型的变量,调用方式pytest.num
{ MP_ROM_QSTR(MP_QSTR_num), MP_ROM_INT(1) },
};
STATIC MP_DEFINE_CONST_DICT(pytest_module_globals, pytest_module_globals_table);
// Define module object.
const mp_obj_module_t pytest_module = {
.base = { &mp_type_module },
.globals = (mp_obj_dict_t *)&pytest_module_globals,
};
// Register the module to make it available in Python.
// MP_QSTR_<module>,这里的module即为最终导入的module名
// import pytest
// 即可导入模块
MP_REGISTER_MODULE(MP_QSTR_pytest, pytest_module);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment