Returning bound methods from an attribute handler

C programming, build, interpreter/VM.
Target audience: MicroPython Developers.
Post Reply
MrSurly
Posts: 7
Joined: Wed Apr 19, 2017 6:08 pm

Returning bound methods from an attribute handler

Post by MrSurly » Wed Apr 19, 2017 6:21 pm

Is this the correct way to implement an .attr handler that must return bound methods? Specifically the mp_obj_new_bound_meth() bits?

Also, how do you make dir(x) work correctly with an .attr handler?

Code: Select all

STATIC mp_obj_t network_bluetooth_service_start(mp_obj_t self_in) {
    NETWORK_BLUETOOTH_DEBUG_PRINTF("network_bluetooth_service_start() FIXME unimplemented\n");

    //FIXME
    return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(network_bluetooth_service_start_obj, network_bluetooth_service_start);

STATIC mp_obj_t network_bluetooth_service_stop(mp_obj_t self_in) {
    NETWORK_BLUETOOTH_DEBUG_PRINTF("network_bluetooth_service_stop() FIXME unimplemented\n");
    //FIXME
    return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(network_bluetooth_service_stop_obj, network_bluetooth_service_stop);

// service attribute handler
STATIC void network_bluetooth_service__attr(mp_obj_t self_in, qstr attr, mp_obj_t *dest) {
    network_bluetooth_service_obj_t* self = (network_bluetooth_service_obj_t*) self_in;

    NETWORK_BLUETOOTH_DEBUG_PRINTF("network_bluetooth_service__attr()\n");  
    NETWORK_BLUETOOTH_DEBUG_PRINTF("attr = %u, dest[0] = %p, dest[1] = %p, MP_QSTR_chars = %u\n", attr, dest[0], dest[1], MP_QSTR_chars);  
    bool storable = false;
    switch(attr) {
        case MP_QSTR_chars:
            if (dest[0] == MP_OBJ_NULL) {  // load
                dest[0] = self->chars;
            } else if (storable && dest[1] != MP_OBJ_NULL) { // store
                if (MP_OBJ_IS_TYPE(dest[1], &mp_type_list) || !MP_OBJ_IS_TYPE(dest[1], &mp_type_tuple)) {
                    self->chars = dest[1];
                    dest[0] = MP_OBJ_NULL;
                }
            } 
            break;
        case MP_QSTR_start:
            if (dest[0] == MP_OBJ_NULL) {
                dest[0] = mp_obj_new_bound_meth(MP_OBJ_FROM_PTR(&network_bluetooth_service_start_obj), self);
            }
            break;
        case MP_QSTR_stop:
            if (dest[0] == MP_OBJ_NULL) {
                dest[0] = mp_obj_new_bound_meth(MP_OBJ_FROM_PTR(&network_bluetooth_service_stop_obj), self);

            }
            break;
    }
}

Post Reply