From cb0fc063edd428e0d7eee69190d2d31b5c9b49a0 Mon Sep 17 00:00:00 2001 From: Paul Sokolovsky Date: Fri, 6 Mar 2015 21:35:26 +0200 Subject: [PATCH] objmemoryview: Introduce mp_obj_new_memoryview(). This follows existing pattern for object constructor API and allows to create memoryview objects e.g. in external modules. --- py/obj.h | 1 + py/objarray.c | 20 ++++++++++++++------ 2 files changed, 15 insertions(+), 6 deletions(-) diff --git a/py/obj.h b/py/obj.h index bfe28e1e41..c58b72f08a 100644 --- a/py/obj.h +++ b/py/obj.h @@ -430,6 +430,7 @@ mp_obj_t mp_obj_new_super(mp_obj_t type, mp_obj_t obj); mp_obj_t mp_obj_new_bound_meth(mp_obj_t meth, mp_obj_t self); mp_obj_t mp_obj_new_getitem_iter(mp_obj_t *args); mp_obj_t mp_obj_new_module(qstr module_name); +mp_obj_t mp_obj_new_memoryview(byte typecode, mp_uint_t nitems, void *items); mp_obj_type_t *mp_obj_get_type(mp_const_obj_t o_in); const char *mp_obj_get_type_str(mp_const_obj_t o_in); diff --git a/py/objarray.c b/py/objarray.c index 30613fcb6e..85b73ae7f5 100644 --- a/py/objarray.c +++ b/py/objarray.c @@ -208,6 +208,17 @@ STATIC mp_obj_t bytearray_make_new(mp_obj_t type_in, mp_uint_t n_args, mp_uint_t #endif #if MICROPY_PY_BUILTINS_MEMORYVIEW + +mp_obj_t mp_obj_new_memoryview(byte typecode, mp_uint_t nitems, void *items) { + mp_obj_array_t *self = m_new_obj(mp_obj_array_t); + self->base.type = &mp_type_memoryview; + self->typecode = typecode; + self->free = 0; + self->len = nitems; + self->items = items; + return self; +} + STATIC mp_obj_t memoryview_make_new(mp_obj_t type_in, mp_uint_t n_args, mp_uint_t n_kw, const mp_obj_t *args) { // TODO possibly allow memoryview constructor to take start/stop so that one // can do memoryview(b, 4, 8) instead of memoryview(b)[4:8] (uses less RAM) @@ -217,12 +228,9 @@ STATIC mp_obj_t memoryview_make_new(mp_obj_t type_in, mp_uint_t n_args, mp_uint_ mp_buffer_info_t bufinfo; mp_get_buffer_raise(args[0], &bufinfo, MP_BUFFER_READ); - mp_obj_array_t *self = m_new_obj(mp_obj_array_t); - self->base.type = type_in; - self->typecode = bufinfo.typecode; - self->free = 0; - self->len = bufinfo.len / mp_binary_get_size('@', bufinfo.typecode, NULL); // element len - self->items = bufinfo.buf; + mp_obj_array_t *self = mp_obj_new_memoryview(bufinfo.typecode, + bufinfo.len / mp_binary_get_size('@', bufinfo.typecode, NULL), + bufinfo.buf); // test if the object can be written to if (mp_get_buffer(args[0], &bufinfo, MP_BUFFER_RW)) {