Parsing a generic constructor from C code

General discussions and questions abound development of code with MicroPython that is not hardware specific.
Target audience: MicroPython Users.
Post Reply
User avatar
chrizztus
Posts: 16
Joined: Thu Feb 23, 2017 3:59 pm

Parsing a generic constructor from C code

Post by chrizztus » Mon Feb 19, 2018 4:32 pm

Hej community,
for my robot I'd like to have a generic constructor in order to initialize a motor either by passing a hash or by an id like below.

Code: Select all

>>> class Motor():
...   def __init__(self,hash=0,id=255):
...     self.hash = hash
...     self.id = id
...   def get_id(self):
...     return self.id
...   def get_hash(self):
...     return self.hash
... 
>>> mot1 = Motor(hash=42)
>>> mot2 = Motor(id=23)
>>> mot1.get_id()
255
>>> mot1.get_hash()
42
>>> mot2.get_id()
23
>>> mot2.get_hash()
0
Now I'd like know how to parse arguments from C in order to return a new object based on given arguments.

Code: Select all

typedef struct _pb_motor_obj_t
{
  mp_obj_base_t base;
  mp_int_t motor_id;
  mp_int_t motor_hash;
}pb_motor_obj_t;

STATIC mp_obj_t motor_obj_make_new( const mp_obj_type_t *type, 
                                  size_t n_args, 
                                  size_t n_kw, 
                                  const mp_obj_t *args )
{
  // check arguments
  mp_arg_check_num(n_args, n_kw, 0, 2, false);
  //TODO: parse arguments
  pb_motor_obj_t *motor = m_new_obj(pb_motor_obj_t);
  motor->base.type = &pb_motor_type;

  // return battery object
  return motor;
}
Maybe someone provide me some example code?!?
Thanks for reading

chrizz

User avatar
dhylands
Posts: 3821
Joined: Mon Jan 06, 2014 6:08 pm
Location: Peachland, BC, Canada
Contact:

Re: Parsing a generic constructor from C code

Post by dhylands » Tue Feb 20, 2018 12:10 am

The example I posted here shows writing C functions with various types of arguments:
https://github.com/dhylands/micropython ... c_sample.c

Normally, if I was expecting an int, I would just call a function like mp_obj_get_int which will throw an exception if the object isn't an int. Here's an example:
https://github.com/micropython/micropyt ... mer.c#L713

User avatar
chrizztus
Posts: 16
Joined: Thu Feb 23, 2017 3:59 pm

Re: Parsing a generic constructor from C code

Post by chrizztus » Tue Feb 20, 2018 10:12 am

Thanks Dave,
I already looked at these examples but I cannot see an example implementing what I was trying to attempt.
So am I right in assuming that initialization like below is not possible with a custom Micropython module?

Code: Select all

mot1 = MOTOR(foo=1)
mot2 = MOTOR(bar=1)
mot3 = MOTOR(foo=1,bar=2)

Post Reply