@@ -238,6 +238,26 @@ STATIC mp_obj_t memoryview_make_new(const mp_obj_type_t *type_in, size_t n_args,
238
238
239
239
return MP_OBJ_FROM_PTR (self );
240
240
}
241
+
242
+ #if MICROPY_CPYTHON_COMPAT
243
+ STATIC mp_obj_t memoryview_cast (const mp_obj_t self_in , const mp_obj_t typecode_in ) {
244
+ mp_obj_array_t * self = MP_OBJ_TO_PTR (self_in );
245
+ const char * typecode = mp_obj_str_get_str (typecode_in );
246
+ size_t element_size = mp_binary_get_size ('@' , typecode [0 ], NULL );
247
+ size_t bytelen = self -> len * mp_binary_get_size ('@' , self -> typecode & ~MP_OBJ_ARRAY_TYPECODE_FLAG_RW , NULL );
248
+ if (bytelen % element_size != 0 ) {
249
+ mp_raise_TypeError (translate ("memoryview: length is not a multiple of itemsize" ));
250
+ }
251
+ mp_obj_array_t * result = MP_OBJ_TO_PTR (mp_obj_new_memoryview (* typecode , bytelen / element_size , self -> items ));
252
+
253
+ // test if the object can be written to
254
+ if (self -> typecode & MP_OBJ_ARRAY_TYPECODE_FLAG_RW ) {
255
+ result -> typecode |= MP_OBJ_ARRAY_TYPECODE_FLAG_RW ; // indicate writable buffer
256
+ }
257
+ return MP_OBJ_FROM_PTR (result );
258
+ }
259
+ STATIC MP_DEFINE_CONST_FUN_OBJ_2 (memoryview_cast_obj , memoryview_cast );
260
+ #endif
241
261
#endif
242
262
243
263
STATIC mp_obj_t array_unary_op (mp_unary_op_t op , mp_obj_t o_in ) {
@@ -691,6 +711,15 @@ const mp_obj_type_t mp_type_bytearray = {
691
711
#endif
692
712
693
713
#if MICROPY_PY_BUILTINS_MEMORYVIEW
714
+
715
+ #if MICROPY_CPYTHON_COMPAT
716
+ STATIC const mp_rom_map_elem_t memoryview_locals_dict_table [] = {
717
+ { MP_ROM_QSTR (MP_QSTR_cast ), MP_ROM_PTR (& memoryview_cast_obj ) },
718
+ };
719
+
720
+ STATIC MP_DEFINE_CONST_DICT (memoryview_locals_dict , memoryview_locals_dict_table );
721
+ #endif
722
+
694
723
const mp_obj_type_t mp_type_memoryview = {
695
724
{ & mp_type_type },
696
725
.name = MP_QSTR_memoryview ,
@@ -700,6 +729,9 @@ const mp_obj_type_t mp_type_memoryview = {
700
729
.binary_op = array_binary_op ,
701
730
.subscr = array_subscr ,
702
731
.buffer_p = { .get_buffer = array_get_buffer },
732
+ #if MICROPY_CPYTHON_COMPAT
733
+ .locals_dict = (mp_obj_dict_t * )& memoryview_locals_dict ,
734
+ #endif
703
735
};
704
736
#endif
705
737
0 commit comments