Search code examples
c++matlabcode-generationmex

coder.ceval struct requires pointer


I am using some external C++ code from within Matlab by calling it via coder.ceval:

coder.ceval('myCppFuncName', coder.wref(mySruct))

This works perfectly as long as myStruct is something simple as

myStruct.a = 0;
myStruct.b = 1;

Now I have a struct which is defined in the C++ header file struct.h:

typedef struct                      
{
  double              x;            
  double              y;            
} myPoint;

typedef struct                      
{
  int                 num_points; 
  myPoint            *points;       // pointer to array of myPoint-structs
} myStruct;

I don't know how to represent the pointer of the C++ struct in Matlab. As I need to define the struct in Matlab I am trying things like:

coder.cstructname(matlab_myPoint,'myPoint','extern');
coder.cstructname(matlab_myStruct,'myStruct','extern');

matlab_myPoint= struct('x',0,'y',0);
matlab_myStruct = struct('num_points',2,'points',myPoint);

ending in an error message

error C2440: '=' : cannot convert from 'myPoint' to 'myPoint *'

In the original C++ struct, a Pointer to an array of structs is used. How can I reproduce this relationship in a Matlab-born struct ? Thank you!


Solution

  • I could finally solve the issue by not passing objects or pointer to objects from Matlab to C but handing over structs instead. The struct in my case contains all the data I need to initialize a new object of the desired class in c.

    In order to achieve this one needs to use the same struct architecture in Matlab and in C.

    Then with

    coder.cstructname(matlab_struct_name,'c_struct_name','extern');
    

    one tells the compiler which C struct is defined by which Matlab struct. The C-Header file has to be specified in the Simulink properties.

    The call of the C-Code in Matlab finally looks like this:

    coder.ceval('gateway', 1, coder.ref(matlab_struct_name), ,coder.wref(matlab_myRet));
    

    where matlab_myRet has been created the same way like matlab_struct_name and represents the return value struct. All values which are written to it inside the C-Code can later be obtained within Matlab:

    matlab_myRet.x(1:5);
    matlab_myRet.y(1:5);
    

    Finally an example of the used struct:

    in Matlab:

    matlab_struct_name.x = 123;
    matlab_struct_name.y = 456;
    
    matlab_myRet.x = zeros(10,1);
    matlab_myRet.y = zeros(10,1);
    

    in C-Code (header):

    typedef struct
    {
        double                  x[5];
        double                  y[5];
    }matlab_struct_name;
    
        typedef struct
    {
        double                  x[10];
        double                  y[10];
    }myReturn;
    

    Hope this helps