Main Content

Integrate External C/C++ Code into金宝appUsingC FunctionBlocks

You can call and integrate your external C code into Simulink®models usingC Functionblocks.C Functionblocks allow you to call external C code and customize the integration of your code using theOutput Code,Start Code,Initialize Conditions Code, andTerminate Codepanes in the block parameters dialog. Use theC Functionblock to:

  • Call functions from external C code including functions defined under namespace, and customize the code for your Simulink models.

  • Preprocess data to call a C function and postprocess data after calling the function.

  • Specify different code for simulation and code generation.

  • Call multiple functions.

  • Initialize and work with persistent data cached in the block.

  • Allocate and deallocate memory.

Use theC Functionblock to call external C algorithms into Simulink that you want to modify. To call a single C function from a Simulink model, use theC Callerblock. To integrate dynamic systems that have continuous states or state changes, use theS-Functionblock.

Note

C99 is the standard version of C language supported for custom C code integration into Simulink.

The following examples useC Functionblocks to calculate the sum and mean of inputs.

Write External Source Files

Begin by creating the external source files.

  1. Create a header file nameddata_array.h.

    / *定义一个结构体称为DataArray * / typedef struct DataArray_tag { /* Define a pointer called pData */ const double* pData; /* Define the variable length */ int length; } DataArray; /* Function declaration */ double data_sum(DataArray data);

  2. In the same folder, create a new file,data_array.c. In this file, write a C function that calculates the sum of input numbers.

    #include "data_array.h" /* Define a function that takes in a struct */ double data_sum(DataArray data) { /* Define 2 local variables to use in the function */ double sum = 0.0; int i; /* Calculate the sum of values */ for (i = 0; i < data.length; i++) { sum = sum + data.pData[i]; } /* Return the result to the block */ return sum; }

Enter the External Code Into金宝app

  1. Create a new, blank model and add aC Functionblock. TheC Functionblock is in theUser-Defined Functionslibrary of the Library Browser.

  2. Double-click theC Functionblock to open the block dialog. Clickto open the Model Configuration Parameters dialog. In theSimulation Targetpane, define your header file underInclude headerson theCode informationtab.

    自定义代码部分的模拟目标ne of Model Configuration Parameters dialog. Code information tab and Include headers field are highlighted. The following text is entered in the field: #include

    Tip

    After you have entered information forSource filein the next step, you can clickAuto-fill from Source filesto have the header file name filled in automatically, using information contained in your source files.

  3. Define the source file underSource fileson theCode Informationtab. To verify that your custom code can be parsed and built successfully, clickValidate custom code.

    自定义代码部分的模拟目标ne of Model Configuration Parameters dialog. Code information tab and Source files field are highlighted. The following text is entered in the field: data_array.c

    Note

    To use aC Functionblock in a For Each subsystem or with continuous sample time, or to optimize the use of the block in conditional input branch execution, all custom code functions called by the block must be deterministic, that is, always producing the same outputs for the same inputs. Identify which custom code functions are deterministic by using theDeterministic functionsandSpecify by functionparameters in theSimulation targetpane. If the block references any custom code global variables, thenDeterministic functionsmust set toAllin order for the block to be used in a For Each subsystem, in conditional input branch execution, or with continuous sample time.

    For an example showing aC Functionblock in a For Each subsystem, seeUse C Function Block Within For Each Subsystem.

  4. In theOutput Codepane of theC Functionblock parameters dialog, write the code that the block executes during simulation. In this example, the external C function computes a sum. In theOutput Codepane, write code that calls thedata_array.cfunction to compute the sum, then computes the mean.

    /* declare the struct dataArr */ DataArray dataArr; /* store the length and data coming in from the input port */ dataArr.pData = &data[0]; dataArr.length = length; /* call the function from the external code to calculate sum */ sum = data_sum(dataArr); /* calculate the mean */ mean = sum / length;

    You can specify code that runs at the start of a simulation and at the end of a simulation in theStart CodeandTerminate Codepanes.

  5. Use theSymbolstable to define the symbols used in the code in the block. Add or delete a symbol using theAddand删除buttons. Define all symbols used in theOutput Code,Start Code,Initialize Conditions Code, andTerminate Codepanes to ensure that ports display correctly.

    In theSymbolstable, for each symbol used in the code in the block, define theName,Scope,Label,Type,Size, andPort, as appropriate.

    Close the block parameters dialog. After filling in the data in the table, theC Functionblock now has one input port and two output ports with the labels specified in the table.

  6. Add aConstantblock to the Simulink canvas that will be the input to theC Functionblock. In theConstantblock, create a random row array with 100 elements. To display the results, attach display blocks to the outputs of theC Functionblock.

Specify Simulation or Code Generation Code

You can specify differentOutput Codefor simulation and code generation for theC Functionblock by definingMATLAB_MEX_FILE. For example, to specify code that only runs during the model simulation, use the following.

#ifdef MATLAB_MEX_FILE /* Enter simulation code */ #else /* Enter code generation code */ #endif

Specify Declaration for Target-Specific Function for Code Generation

For code generation purposes, if you do not have the external header file with the declaration of a function (such as a target-specific device driver) that you want to call from theC Functionblock, you can include a declaration with the correct signature in theOutput Codepane of the block. This action creates a function call to the expected function when code is generated, as in the following example:

#ifndef MATLAB_MEX_FILE extern void driverFcnCall(int16_T in, int16_T * out); driverFcnCall(blockIn, &blockOut); #endif

See Also

Functions

Objects

Blocks

Related Topics