Calllib function error using with struct array
16 views (last 30 days)
Show older comments
Hi guys, I am trying to use shared library produced from C code. My purpose is send address of struct_1 to C function as an input, then change values in struct_1 in C function and take back address of struct_1 from C function to the MATLAB.
I have a structure such as struct_1 = struct('Var_1', var_1, 'Var_2', [var_2,var_2], 'Var_3', char(zeros(1,10))). I constructed this struct in MATLAB and same struct constructed also in C header file. Type of Var_1 is structure and type of Var_2 is 1x2 array which has a struct component. Additionally, Var_3 is a character array. I defined var_1 and var_2 structures before construct struct_1.
When I used ' calllib('libStruct', 'structFnc', struct_1); ', I took 'Cannot convert data value for field Var2 due to error: Array must be numeric or logical or a pointer to one' error.
I tried 'struct_1.Var_2 = libpointer('cstring');' but Var_2 variable become a 1x1 libpointer, actually it was a struct array. I took same error for char array variable, Var_3.
How can I use structure which is constructed with struct array and char array members in calllib function? I would be very glad if you help!
0 Comments
Answers (1)
Guillaume
on 16 Mar 2020
It's a slightly different procedure for passing structures between matlab and a C library. Internally, matlab structures are very different from C structures. See libstruct and associated examples.
Note that the equivalent of your matlab structure in C would be:
struct c_struct {
double Var_1;
double *Var_2;
char *Var_3;
};
Also note that in the above the C library would have no way of knowing the size of the double and char arrays so would need another way of knowing these size (for the char, possibly it's zero terminated).
4 Comments
Guillaume
on 16 Mar 2020
Ah yes. I'm not sure why. You can fix this by converting your matlab char vector to uint8:
s = libstruct(struct('Var_1', 1, 'Var_2', [2, 3], 'Var_3', uint8('abcdefghij')));
See Also
Categories
Find more on Call C from MATLAB in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!