pythonconsolecaplcanoe

How to call Python functions from CAPL?


I have a Python module, say module.py, which has several functions like below.

"""module.py"""
class myclass: 
    def foo(self, arg1: str, arg2: int) -> int: 
        print(f"foo called with args - {arg1}, {arg2}") 
        return arg2;

So far I am able to run a Python script as a whole to some extent. But I want to call foo() from a CAPL function which looks like below.

variables
{
    int return_value;
}

void GetFooResult()
{
    //insert call to python function here and get the return_value
    write(return_value);
}

Is there a way to achieve this? I don't mind if its complicated but I need some elaboration as I am a novice to CANoe.


Solution

  • As suggested in comments (though harsh they did help me get started, so coming to SO was not a waste after all!) building and using a CAPL-to-C-to-Python DLL is the solution. We might use C++ or any other supported language in place of C but Python embedding in C is well documented.

    Below is the procedure:

    Step 1: Add Python embedding code to the sample CAPLdll.cpp.

    Reference link from comments for Python embedding

    #include <Python.h>
    
    int32_t CAPLEXPORT CAPLPASCAL capl_foo() {
    //Python embedding done here
    }
    
    
    Step 2: Add an entry in the export table for the above function.

    Reference link from comments for exporting functions

      {"my_foo", (CAPL_FARCALL)capl_foo, "CAPL_DLL", "Python calls", 'L', 0, "", "", {""}},
    
    Step 3: Build the CAPLdll project
    Step 4: Call your Python function from the CAPL node
    on key 'p'
    {
      int result;
      result = my_foo();
      writeLineEx(1,1,"");
      write("Result is %d", result);
    }
    
    Step 5: Run the simulation
    [I] [Program / Model]   Use the keyboard to control the program
    [I] [Program / Model]   <1> Direct call of a CAPL Callback function
    ...
    [I] [Program / Model]   <p> Run Py foo
    [I] [Program / Model]   <h> Help
    [I] [Program / Model]   --------------------------------------------------------------
    [*] [Program / Model]   Result is 42
    [I] [Program / Model]   
    [*] [Program / Model]   Result is 42
    [I] [Program / Model]