【问题标题】:How to give a structure with arrays in simulink to a custom C code function?如何将 simulink 中的数组结构提供给自定义 C 代码函数?
【发布时间】:2015-01-20 08:33:59
【问题描述】:

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

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

    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 函数中将它们声明为标量,它就可以工作。 有人看到我做错了吗?

【问题讨论】:

    标签: c matlab simulink matlab-coder


    【解决方案1】:

    编译代码

    要编译代码,我添加了:

    #include "mystruct.h"
    

    在模拟目标->自定义代码->头文件部分。可能还需要在该窗格上添加所需的包含路径。

    兼容性问题

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

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

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

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

    具有内联数组的结构已经有 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));
      }
      

    【讨论】:

      【解决方案2】:

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

      【讨论】:

      • 据我了解,如果它不包含在“自定义代码”部分中,则只需将其放在“HeaderFile”上。但是我试过了,还是不行。
      猜你喜欢
      • 1970-01-01
      • 2021-09-04
      • 1970-01-01
      • 2020-12-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多