MATLAB: Is it possible to call JAVA code from within Simulink
calljavas-functionsimulink
I would like to use Simulink to call, run, or use a JAVA program. I wonder if this can be done using an S-function.
Best Answer
There is no direct functionality to call JAVA code from Simulink. One possible workaround is to use an S-function block. The S-function blocks are written in MATLAB, C, C++ or Ada code.
In the attached example, we show how a Level-2 MATLAB S-function block with appropriate block parameters and callbacks setup ; is able to call java code.
A simple Java call example is provided in the attached files wherein a Java String is created and the raw bytes are extracted from it and displayed. The Java Code has been placed in the 'output' callback of the S-Function, so it executes every time an output needs to be produced. Please look into the MATLAB Code of the S-Function block by right-clicking the S-Function block and choosing 'Look Under Mask'. This example has been created by modifying the MATLAB Times Two S-Function example that ships with MATLAB.
Please note that using Java calls with S-function may lead users to believe that it may be possible to do the same in Embedded MATLAB function block. However, this is not advisable because if you need to import any of the Java libraries using the 'IMPORT' function, this can not be done as Embedded MATLAB Fcn Block does not support the IMPORT command.
For example, if the S-function name is 'myfunction', define a variable 'x' in the MATLAB workspace containing the S-function name by executing the following command at the MATLAB command prompt.
x='myfunction';
Now enter the following statement as the 'S-function name' parameter in the S-function block.
sprintf(x)
For more information on the function SPRINTF, type the following command at the MATLAB command prompt.
Having a reference to a Java class or an IMPORT statement which imports that class anywhere in a MATLAB file will cause the MATLAB interpreter to load that class when the file is first loaded. If a Java class has a static block, that code will be executed when the class is loaded. If there is an error in the static block of code, an error will occur. This loading happens on a per-file bases (not on a function basis) so the main function and all sub-functions and nested-functions will all be parsed and java classes loaded at the same time. This is expected and required behavior for the MATLAB interpreter to be able to resolve java class names.
In order to prevent the Java classes from being loaded and prevent their static blocks from being executed, you will need to separate out any of the calls to the Java class into a separate file which is never accessed.
Best Answer