Skip to content

Commit f6d99bc

Browse files
committed
py/dynruntime.h: Add implementation of mp_obj_cast_to_native_base.
1 parent 9344e87 commit f6d99bc

File tree

1 file changed

+17
-0
lines changed

1 file changed

+17
-0
lines changed

py/dynruntime.h

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@
3131

3232
#include "py/nativeglue.h"
3333
#include "py/objstr.h"
34+
#include "py/objtype.h"
3435

3536
#undef MP_ROM_QSTR
3637
#undef MP_OBJ_QSTR_VALUE
@@ -106,6 +107,7 @@ static inline void *m_realloc_dyn(void *ptr, size_t new_num_bytes) {
106107
#define mp_obj_new_list(n, items) (mp_fun_table.new_list((n), (items)))
107108

108109
#define mp_obj_get_type(o) (mp_fun_table.obj_get_type((o)))
110+
#define mp_obj_cast_to_native_base(o, t) (mp_obj_cast_to_native_base_dyn((o), (t)))
109111
#define mp_obj_get_int(o) (mp_fun_table.native_from_obj(o, MP_NATIVE_TYPE_INT))
110112
#define mp_obj_get_int_truncated(o) (mp_fun_table.native_from_obj(o, MP_NATIVE_TYPE_UINT))
111113
#define mp_obj_str_get_str(s) ((void*)mp_fun_table.native_from_obj(s, MP_NATIVE_TYPE_PTR))
@@ -125,6 +127,21 @@ static inline mp_obj_t mp_obj_new_str_of_type_dyn(const mp_obj_type_t *type, con
125127
}
126128
}
127129

130+
static inline mp_obj_t mp_obj_cast_to_native_base_dyn(mp_obj_t self_in, mp_const_obj_t native_type) {
131+
const mp_obj_type_t *self_type = mp_obj_get_type(self_in);
132+
133+
if (MP_OBJ_FROM_PTR(self_type) == native_type) {
134+
return self_in;
135+
} else if (self_type->parent != native_type) {
136+
// The self_in object is not a direct descendant of native_type, so fail the cast.
137+
// This is a very simple version of mp_obj_is_subclass_fast that could be improved.
138+
return MP_OBJ_NULL;
139+
} else {
140+
mp_obj_instance_t *self = (mp_obj_instance_t*)MP_OBJ_TO_PTR(self_in);
141+
return self->subobj[0];
142+
}
143+
}
144+
128145
static inline void *mp_obj_str_get_data_dyn(mp_obj_t o, size_t *l) {
129146
mp_buffer_info_t bufinfo;
130147
mp_get_buffer_raise(o, &bufinfo, MP_BUFFER_READ);

0 commit comments

Comments
 (0)