MATLAB: Does the generated Simulink block have an incorrect number of inputs/outputs when I generate the block with the “legacy_code” command

simulink

When I use the "legacy_code" command to generate a Simulink block from legacy C code (i.e. from ".c" files and ".h" files), I only see one inport, one outport, and one block parameter.
However, my C code explicitly states that there are two inports "in1" and "in2", one outport, and one block parameter "gain", so what could be going wrong? How can I generate a block with the correct number of inports/outports?

Best Answer

This can happen if the generated s-function is not compiled before generating the Simulink block. In this case the block default to one inport and one output. As an example, take the following C code:
"gain.h"
#ifndef _GAIN_H_
#define _GAIN_H_
#include "your_types.h"
extern float gainScalar(const float in, const float in2, const float gain);
#endif
"gainScalar.c"
#include "your_types.h"
#include "gain.h"
float gainScalar(const float in, const float in2, const float gain)
{
return (in+in2*gain);
}
If we use the "legacy_code" function to generate a Simulink block from this C code, we must make sure to compile the code first so that we get the correct number of inports and outports. Here is an example of INCORRECT code that produces only one inport and one outport:
% generateBlock.m

def = [];
def = legacy_code('initialize');
def.SFunctionName = 'sldemo_sfun_st_parameterized';
def.OutputFcnSpec = 'single y1 = gainScalar(single u1, single u2, single p1)';
def.HeaderFiles = {'gain.h'};
def.SourceFiles = {'gainScalar.c'};
def.IncPaths = {''};
def.SrcPaths = {''};
def.SampleTime = 'parameterized';
legacy_code('sfcn_cmex_generate', def);
legacy_code('slblock_generate', def);
We can see that executing this code produces the wrong Simulink block. If instead we execute the following code, we get the correct (two-inport, one-outport) block:
% generateBlock.m
def = [];
def = legacy_code('initialize');
def.SFunctionName = 'sldemo_sfun_st_parameterized';
def.OutputFcnSpec = 'single y1 = gainScalar(single u1, single u2, single p1)';
def.HeaderFiles = {'gain.h'};
def.SourceFiles = {'gainScalar.c'};
def.IncPaths = {''};
def.SrcPaths = {''};
def.SampleTime = 'parameterized';
legacy_code('sfcn_cmex_generate', def);
legacy_code('compile', def); % COMPILE!
legacy_code('slblock_generate', def);