Attempt to allocate a bytearray behind the sCenes

This rebuilds the crucial parts of MicroPython's bytearray creation and calls it quietly from inside the C-bindings, avoiding the need for a bytearray to be passed in by the user.

Whether this magically holds a reference and evades GC remains to be seen.
This commit is contained in:
Phil Howard 2021-01-20 23:46:13 +00:00
parent 032d509d8e
commit 7f05e35622
3 changed files with 21 additions and 7 deletions

View File

@ -1,4 +1,6 @@
#include "pico_display.h"
#include "py/binary.h"
#include "py/objarray.h"
/***** Constants *****/
enum buttons
@ -9,13 +11,25 @@ enum buttons
BUTTON_Y,
};
mp_obj_t alloc_new_bytearray(int len) {
int typecode_size = mp_binary_get_size('@', BYTEARRAY_TYPECODE, NULL);
mp_obj_array_t *o = m_new_obj(mp_obj_array_t);
o->base.type = &mp_type_bytearray;
o->typecode = BYTEARRAY_TYPECODE;
o->free = 0;
o->len = len;
o->items = m_new(byte, typecode_size * o->len);
memset(o->items, 0, len);
return MP_OBJ_FROM_PTR(o);
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// picodisplay Module
////////////////////////////////////////////////////////////////////////////////////////////////////
/***** Module Functions *****/
STATIC MP_DEFINE_CONST_FUN_OBJ_1(picodisplay_init_obj, picodisplay_init);
STATIC MP_DEFINE_CONST_FUN_OBJ_0(picodisplay_init_obj, picodisplay_init);
STATIC MP_DEFINE_CONST_FUN_OBJ_0(picodisplay_get_width_obj, picodisplay_get_width);
STATIC MP_DEFINE_CONST_FUN_OBJ_0(picodisplay_get_height_obj, picodisplay_get_height);
STATIC MP_DEFINE_CONST_FUN_OBJ_0(picodisplay_update_obj, picodisplay_update);

View File

@ -12,12 +12,10 @@ PicoDisplay *display;
extern "C" {
#include "pico_display.h"
mp_obj_t buf_obj;
mp_obj_t picodisplay_init(mp_obj_t buf) {
mp_obj_t picodisplay_init() {
mp_obj_t ba = alloc_new_bytearray(PicoDisplay::WIDTH * PicoDisplay::HEIGHT * sizeof(uint16_t));
mp_buffer_info_t bufinfo;
mp_get_buffer_raise(buf, &bufinfo, MP_BUFFER_RW);
buf_obj = buf;
mp_get_buffer_raise(ba, &bufinfo, MP_BUFFER_RW);
display = new PicoDisplay((uint16_t *)bufinfo.buf);
display->init();
return mp_const_none;

View File

@ -2,8 +2,10 @@
#include "py/runtime.h"
#include "py/objstr.h"
extern mp_obj_t alloc_new_bytearray(int len);
// Declare the functions we'll make available in Python
extern mp_obj_t picodisplay_init(mp_obj_t buf);
extern mp_obj_t picodisplay_init();
extern mp_obj_t picodisplay_get_width();
extern mp_obj_t picodisplay_get_height();
extern mp_obj_t picodisplay_set_backlight(mp_obj_t brightness_obj);