Search code examples
simicsdml-lang

How to call Python functions from DML?


I would like to have a DML device with interfaces and register banks as the TOP-level of my device but offload processing to Python. Is there a lightweight method of calling into Python from DML?

This post How can I unit test a specific DML method? addresses calling from Python into DML, but I am interested in the reverse.

I think I can create a bunch of custom interfaces to do this, but I'm interested to know if there's a better way.


Solution

  • Implementing parts of a device in Python can make sense, in particular for code that seldom is invoked (user interaction comes to mind), and when faced with tasks like string manipulation where the shortcomings of a C-like language is particularly painful, or when code sharing with CLI commands is desired.

    You can use the SIM_call_python_function API to call out to Python from DML. The function uses the equivalent of eval on the passed string, so you can find a module-local function by __import__:

    local attr_value_t a = SIM_make_attr_list(0);
    local attr_value_t result = SIM_call_python_function(
        "__import__('simics').SIM_version", &a);
    log info: "%s", SIM_attr_string(result);
    SIM_attr_free(&a);
    SIM_attr_free(&result);
    

    This API is admittedly not very pretty. Parts of the standard lib for DML 1.2 is in fact written in Python and uses the internal function VT_call_python_module_function for this task instead. That API is nicer, but we cannot recommend use of VT_ functions outside the core Simics team.