Search code examples
c++matlabarduinosimulinkmatlab-coder

Matlab with external C++ function: coder.ceval pass a structure to a function


I’m trying to pass a Structure from a Matlab function in Simulink to an external C++ function using the coder.ceval() and the coder.cstructname(). When I try to run the code on an Arduino Due board using the deploy to hardware tool in Simulink I get the error:

error: invalid use of incomplete type 'struct MyStruct' 
error: forward declaration of 'struct MyStruct'

I’m using the example code from mathworks but use a c++ function instead of a c function:

Header use_struct.h:

#include <tmwtypes.h>

typedef struct MyStruct
{
    double s1;
    double s2;
} MyStruct;

void use_struct(struct MyStruct *my_struct);

C++ function use_struct.cpp:

 #include <stdio.h>
 #include <stdlib.h>
// #include "use_struct.h"  // Doesn’t work when I include it here


extern “C” void use_struct(struct MyStruct *my_struct)
{
  double x = my_struct->s1;
  double y = my_struct->s2;
}

Matlab function:

structVar.s1 = 1;
structVar.s2 = 2;

if strcmp(coder.target,'rtw'),


coder.cinclude('use_struct.h');
coder.cstructname(structVar, 'MyStruct', 'extern');

coder.ceval('use_struct', coder.ref(structVar));

end

I need it to be a C++ function for the later code. However I also tried it with a c function without the extern “C” but it doesn’t work anyway. Can anyone help me with this problem?


Solution

  • I found the solution. I had to include the c header use_struct.h in the use_struct.cpp also with:

    extern "C"
     {
       #include "use_struct.h"
     }