How can I pass a constant C string to a function in the code generated from Embedded MATLAB in Real-Time Workshop Embedded Coder 5.1 (R2008a)?

9 views (last 30 days)
In an Embedded MATLAB function, I can call a custom C function with EML.CEVAL.
It I pass a string as an argument, the generated code use a pointer to an array of char. I would like to pass the actual string.
For example, when generating C code for :
eml.ceval('MyCExternalFunction', arg1,['MyString' char(0)]);
I get :
MyCExternalFunction (arg1, tmp)
where tmp is a pointer to "MyString"
I would like to have :
MyCExternalFunction (arg1, "MyString")

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 8 Dec 2009
When using strings in Embedded MATLAB, there is one first thing that is important to know :
'MyString' in MATLAB and "MyString" in C are not equivalent. In C, strings are null-terminated, whereas in MATLAB we treat them as character arrays (without null-termination). Therefore, it is not correct to pass
'MyString' to a C function and assume it is treated as a "MyString" in C.
Thus, the correct code for
eml.ceval('MyCExternalFunction', arg1, 'MyString');
should be:
eml.ceval('MyCExternalFunction', arg1, ['MyString' 0]);
Then, in order to pass a constant C string to a custom C function, one can use the EML.OPAQUE instruction. For example, EML.CEVAL call becomes :
eml.ceval('MyCExternalFunction', arg1, eml.opaque('const char *', '"MyString"'));
and that will just "glue-in" the "MyString" constant in the generated code :
MyCExternalFunction(arg1, "MyString");
Note : refer to related solution 1-7K299R for Null-terminated C strings.
  1 Comment
cui,xingxing
cui,xingxing on 18 Feb 2023
what about R2022b now? pass a string scalar to matlab coder to generate C code may does't work!
for example :
mystring = "C:/temp/1.jpg";
mychar_string = char(mystring);
coder.ceval('MyExternalFunction',coder.rref(mychar_string))
where 'MyExternalFunction' declaration is :
void MyExternalFunction(const char* mychar_string);
However, matlab variable `mychar_string` pass to C is `C:/temp/1.jpg<*>`, one extra * garbled character at the end. how to fix it?
in generate C code

Sign in to comment.

More Answers (0)

Categories

Find more on Holidays / Seasons in Help Center and File Exchange

Products


Release

R2008a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!