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

Embedded Coderinline()referencestringvalue

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")

Best Answer

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.