MATLAB: How to access an array of structs inside a Simulink.Parameter using the C API

capiEmbedded Coderrtw_modelmaprtwcapisimulink coder

 
I am trying to use the C API to access tunable parameters in my generated code. The Simulink.Parameter is of type struct with fields that are also structs:
Everything works fine when I only use 1×1 structs (such as 'plainstruct' from above) but I am having trouble accessing the array of structs ('arraystruct' from the image above) using the C API.
Are arrays of structs supported when using the C API to access parameters? If they are supported, how can you access the array of structs? 

Best Answer

Arrays of structs are supported when using the C API. Since the C API macros rely on parameter addresses, it can be difficult to determine what the return type of the macros should be (to cast the pointers appropriately). To illustrate the best practice in this regard, I have put together a simple example (see capi_exampl.zip) demonstrating how to use buses as the data type for the "Simulink.Parameter" to make this easier. This example also demonstrates the usage of the C-API to access elements of structured parameters.
Here are instructions for running the model:
1) Run the "create_mySimParam.m" script
2) Load the bus definitions
load('busDataTypeDefinitions.mat')
3) Open "CAPI_example.slx" and Build the model (Ctrl+b)
4) Then run the executable generated using the following command in the MATLAB Command Window:
!CAPI_example.exe
 
Here are some notes about the example:
  •   Note that in "create_mySimParam.m" the "Simulink.Parameter" is defined. The parameter used in the model is a structured Simulink parameter and I have made the datatype of the parameter to be Bus data type. Assigning the datatype of a structure to be bus datatype allows you to control the naming of the datatype appearing in the code and thus would greatly simplify accessing the parameter through the C API. In this example, I have set the datatype of the Simulink parameter to "simParamDataType" which is structured as below:
  • In this example, through the C-API, I want to access the value of "mySimParam.arraystruct(2).a". The code used to do this can be found in the "Initialize Function" section of the Custom Code pane (Configuration Parameters > Code Generation > Custom Code). For your convenience, here is the snippet of code used:
  • Please note that assigning the parameter type to be a custom bus ("simParamDataType") simplified casting the "Simulink.Parameter" model parameter to the correct datatype on Line 17 from the code above
  • The fact that "mySimParam.arraystruct" is a struct array is captured in the "Dimensions" property of the Bus Element named "arraystruct":
This example can provide a starting point which you will need to adapt to your use-case. If you have questions about the macros used, then please refer to the files "rtw_modelmap.h" and "rtw_capi.h", located in "matlabroot/rtw/c/src".