MATLAB: Put a .m file into the simulink ,why can’t work

matlab codersimulinksimulink mfuction

I pulled a m function model and code as followed
function y = fcn(u1,u2)
coder.extrinsic('loadlibrary','libfunctions','calllib','unloadlibrary');
loadlibrary('DLL_ADD','DLL_ADD.h');
libfunctions DLL_ADD;
G=calllib('DLL_ADD','Add',u1,u2);
unloadlibrary('DLL_ADD');
y = G;
but there are some errors I can't figure out
Function output 'y' cannot be an mxArray in this context. Consider preinitializing the output variable with a known type.
Function 'MATLAB Function1' (#65.0.232), line 1, column 1:
"function y = fcn(u1,u2)"
Launch diagnostic report.
Errors occurred during parsing of MATLAB function 'MATLAB Function1'(#65)

Best Answer

Since you have declared calllib as an extrinsic function using coder.extrinsic, Simulink is unable to determine the type of 'y' which is required to generate C code from the MATLAB code, for execution. You can preinitialize the size and type of 'y' as the error suggests.
For example, assuming that 'y' is the same size and type as 'u1':
function y = fcn(u1,u2)
coder.extrinsic('loadlibrary','libfunctions','calllib','unloadlibrary');
loadlibrary('DLL_ADD','DLL_ADD.h');
libfunctions DLL_ADD;
G=calllib('DLL_ADD','Add',u1,u2);
unloadlibrary('DLL_ADD');
y = coder.nullcopy(zeros(size(u1)));
y = G;
Related Question