lingua-franca icon indicating copy to clipboard operation
lingua-franca copied to clipboard

Calling LF as a library function.

Open stustd opened this issue 1 year ago • 3 comments

A nontrivial application may consist of a complex of sub-LF applications each of which is called upon according to some underlying app logic (e.g. various simulators for different purposes). In order to enable such configuration it would be handy if each LF reactor model could be called as a library function, e.g. int main_{i}(...) instead of the default int main(...), and then linked against the (C/C++) glue code. Is that an option?

stustd avatar Jul 08 '24 11:07 stustd

This seems doable. In the C target, the generated main function looks like this:

int main(int argc, const char* argv[]) {
    return lf_reactor_c_main(argc, argv);
}

Presumably, if this main function were not present, the application could call lf_reactor_c_main from its own main function. However, currently, I suspect this would support only one embedded LF program. Supporting more than one seems likely to result in duplicate symbol errors when linking.

edwardalee avatar Jul 08 '24 11:07 edwardalee

A solution could be prefixing both the library call and all global variables with the main LF file name. In that way each LF model will be uniquely defined.

stustd avatar Jul 08 '24 17:07 stustd

This is already how the C++, Rust and Typescript targets are designed. The runtime is implemented as a standalone library (i.e. it could be used in plain C++/Rust/Typescript code) and the LF code generator implements a layer on top that allows you to more conveniently define reactors. The LF code generator also produces a main function. However, you could simply write your own. All it takes to start a C++ reactor program is to instantiate the Envioronment object which contains the scheduler, instantiate the main reactor class, and then instruct the runtime to start executing this reactor.

There are a couple of improvements that could be made to make this easier. In particular, I think it would be nice to make the individual LF files independent Cmake targets. This would allow you to more conveniently import and link against a specific reactor.

cmnrd avatar Jul 10 '24 07:07 cmnrd