Check signature of handler

C programming, build, interpreter/VM.
Target audience: MicroPython Developers.
Post Reply
ttmetro
Posts: 104
Joined: Mon Jul 31, 2017 12:44 am

Check signature of handler

Post by ttmetro » Wed Jul 24, 2019 5:22 pm

How do I check the signature of a function?

I define it in Python

Code: Select all

def handler_function(arg1, arg2):
    pass
and then call it with the following C code:

Code: Select all

mp_call_function_2(handler_function, arg1, arg2)
This works well, but crashes the VM if the handler function is not declared with the correct signature (two arguments).

How can I verify the handler signature in C (i.e. that it takes exactly two arguments)?

Presently I just check that it's a function:

Code: Select all

    if (MP_OBJ_IS_FUN(handler_obj) || MP_OBJ_IS_METH(handler_obj)) {
        stdout_handler = handler_obj;
    } else {
        mp_raise_ValueError("function expected");
    }
Bernhard Boser

User avatar
jimmo
Posts: 2754
Joined: Tue Aug 08, 2017 1:57 am
Location: Sydney, Australia
Contact:

Re: Check signature of handler

Post by jimmo » Thu Jul 25, 2019 1:11 pm

Hi,

When I do this in C (inside a function callable from Python taking a single argument).

Code: Select all

mp_call_function_2(obj, mp_const_none, mp_const_none);
where obj was the argument passed into the function.

Then from the REPL:

Code: Select all

>>> def bar():
...     print('bar')
...    
>>> my_c_function(bar)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: bar() takes 0 positional arguments but 2 were given
>>> 
So it's unexpected that you're seeing a VM crash...?

To answer your question though -- it isn't easy to answer the question "how many params does a function take".

For example:

Code: Select all

def handler_function(*args):
  pass
Internally in the VM, the signature is represented differently depending on how it was defined (i.e. C, inline asm, regular bytecode, etc). The way this is implemented, it's the responsibility of the callee to figure out if it has been given the right number of arguments. Look at fun_builtin_var_call and fun_bc_call for more information for two of those cases.

ttmetro
Posts: 104
Joined: Mon Jul 31, 2017 12:44 am

Re: Check signature of handler

Post by ttmetro » Thu Jul 25, 2019 4:18 pm

Thanks. What I actually did is forward everything that's written to stdout to the handler. The exception prints the error message - and results in an infinite loop.

Confused myself; should have tried a simpler example (like what I posted).
Bernhard Boser

Post Reply