如何在simulink中为自定义C代码函数提供数组结构?

时间:2015-01-20 08:33:59

标签: c matlab simulink matlab-coder

我正在尝试在Simulink中为C函数提供结构。到目前为止我的步骤:

  • 包含.h& .c配置参数自定义代码。我的标题有一个结构defind:

    typedef struct mystruct   
    {  int m; 
    int *i; 
    double *x;}mystruct
    
  • 现在在Simulink下的MATLAB函数中:

    function y = fcn(u)%#codegen   
    m=int32(1);
    i=zeros(10,1,'int32');
    x=zeros(10,1); 
    s.m=m;
    s.i=i;
    s.x=x;
    coder.cstructname(s,'mystruct','extern');
    D=int32(0);
    D=coder.ceval('accesmystruct',coder.ref(s));
    y=10;
    

如果我运行代码,我会从代码生成中得到一个很长的错误,表明它无法用c代码编译。错误是:

   c2_Test2.c 
   c2_Test2.c(57) : error C2143: syntax error : missing ')' before '*' 
   c2_Test2.c(57) : error C2081: 'cs_size' : name in formal parameter   list illegal 
   c2_Test2.c(57) : error C2143: syntax error : missing '{' before '*' 
   c2_Test2.c(57) : error C2059: syntax error : ')' 
   c2_Test2.c(60) : error C2143: syntax error : missing ')' before '*'   
   ....

只有当我将两个变量ix声明为指针时才会发生这种情况。如果我在标题和MATLAB函数中声明它们是标量,它就可以工作。 有没有人看到我做错了什么?

2 个答案:

答案 0 :(得分:1)

让代码编译

为了获得编译代码我添加了:

#include "mystruct.h"
<模拟目标 - &gt;自定义代码 - &gt;标题文件部分中的

。也可能需要在该窗格上添加所需的包含路径。

兼容性问题

执行上述操作后,代码在运行时崩溃。问题是mystruct的定义不是MATLAB Coder所期望的。

当你定义一个内部有固定大小数组的MATLAB结构时,MATLAB Coder生成的类型使用C结构内部的静态数组,如:

typedef struct {
  int32_T m;
  int32_T i[10];
  real_T x[10];
} mystruct;

如果您从slprj电话中删除了'extern',则可以在coder.cstructname目录的代码中看到这一点。

具有内联数组的结构已经具有由C编译器为数组分配的内存。但是,当字段是指针时,有人需要为数据分配空间,这在此处尚未完成。

我看到了几个选项:

  • 省略'extern'并允许MATLAB Coder / Simulink生成类型定义
  • 使用数组声明您的外部结构,而不是ix
  • 的指针
  • 在写入或读取结构之前,将其传递给另一个为字段分配内存的C函数:

    function y = fcn(u)
    %#codegen
    m=int32(1);
    i=zeros(10,1,'int32');
    x=zeros(10,1);
    s = coder.nullcopy(struct('m',m,'i',i,'x',x));
    coder.cstructname(s,'mystruct');
    coder.ceval('initmystruct',coder.wref(s),int32(numel(i)),int32(numel(x)));
    s.m=m;
    s.i=i;
    s.x=x;
    

    在C:

    /* Example of initmystruct with no error checking */
    /* int is the size type assuming it matches int32 */
    /* in the MATLAB coder.ceval call                 */
    void initmystruct (mystruct *s, int szi, int szx)
    {
        s->i = malloc(szi*sizeof(*s->i));
        s->x = malloc(szx*sizeof(*s->x));
    }
    

答案 1 :(得分:0)

根据cstructname的文档,需要使用'Headerfile'输入参数指定头文件。