MATLAB: Do I receive a crash when I perform file I/O operations within Embedded MATLAB using the EML.CEVAL directive in MATLAB 7.8 (R2009a)

MATLABmatlab coder

I have MATLAB code wherein the EML.CEVAL directive is used to read data from a file.The compilation of the code using EMLC is successful. However, when I attempt to run the MEX file, MATLAB crashes with the following stack trace:
Stack Trace:
[0] ntdll.dll:0x7c901010(0, 0x00c2b701, 0x0cfc9968 "initTargetRCS_eml", 164)
[1] msvcrt.dll:0x77c4120f(0x00c2b701, 1, 165, 0)
[2] eml_TargetRCS.mexw32:0x0cbf166c(0x00c2cbbc "ZZúÿZZúÿZZúÿZZúÿZZúÿZZúÿZZúÿZZúÿ..", 0, 0x40390000, 0)
[3] eml_TargetRCS.mexw32:0x0cbf5826(0x00c2e940, 0x00c2e2a0 "ZZúÿ", 0x2424f998 "¤TàzõU", 0)
[4] eml_TargetRCS.mexw32:0x0cbf5e4c(1, 0x00c2e9d0, 3, 0x00c2e940)
[5] libmex.dll:_mexRunMexFile(1, 0x00c2e9d0, 3, 0x00c2e940) + 132 bytes
[6] libmex.dll:private: void __thiscall Mfh_mex::runMexFileWithSignalProtection(int,struct mxArray_tag * *,int,struct mxArray_tag * *)(1, 0x00c2e9d0, 3, ……..
To reproduce the issue, create a text file (blank) called 'data.txt'. Then write a simple Embedded MATLAB function as follows:
function r = testScript(u)
%#eml
fid = eml.opaque('FILE *', 'NULL');
targfile = 'data.tbl';
targfileaction = 'rb';
fid = eml.ceval('fopen',eml.ref(targfile), eml.ref(targfileaction));
r=0;
eml.ceval('fclose',fid);
end
Then execute,
% Compile testScript
emlc testScript
% Execute the resulting MEX file
data = testScript(10);

Best Answer

The issue is that MATLAB strings are not null-terminated. You have to manually create a C-style string when using EML.CEVAL.
For example, the following is what testScript.m should read:
function r = testScript1(u)
%#eml
fid = eml.opaque('FILE *', 'NULL');
targfile = ['data.tbl' char(0)];
targfileaction = ['rb' char(0)];
fid = eml.ceval('fopen', targfile, targfileaction);
r=0;
eml.ceval('fclose',fid);
end