How to convert a function using mex code with the Matlab Coder

2 views (last 30 days)
Robert on 15 Apr 2015
Commented: Robert on 22 Apr 2015
I am trying to convert my project into C code using the Matlab Coder but it is running into an error when it comes to the 'written for mex' C code part.
The error is:
>> coder -build test_mex.prj??? C function calls always return scalar values but a non-scalar value is expected here.
Error in ==> test_Coder_with_mex Line: 13 Column: 5
Code generation failed: Open error report.
My test code is:
function Pts_out = test_Coder_with_mex
Pts_in = [1,1,1; 1,1,2; 1,2,1; 2,1,1; 1,2,2; 2,1,2; 2,2,1; 2,2,2];
Pts_out = zeros(8,3);
Pts_ctrl_in = [Pts_in(1,:); Pts_in(4,:); Pts_in(8,:)];
Pts_ctrl_out = [0,0,0; 2,1,1; 2,3,2];
D_hnd_mesh = [0 1 1.73205080756888;1 1.41421356237310 1.41421356237310;1 1.41421356237310 1.41421356237310;1 0 1.41421356237310;1.41421356237310 1.73205080756888 1;1.41421356237310 1 1;1.41421356237310 1 1;1.73205080756888 1.41421356237310 0];
% running in MATLAB
Pts_out = MLSsubroutine_C(Pts_in, Pts_ctrl_in, Pts_ctrl_out, 2, D_hnd_mesh);
% running by coding
Pts_out = coder.ceval('MLSsubroutine_C',Pts_in, Pts_ctrl_in, Pts_ctrl_out, 2, D_hnd_mesh);
The C function is not running with a return value but with the mex specific:
void mexFunction(int nlhs, mxArray *plhs[], /* Output variable */
int nrhs, const mxArray *prhs[]) /* Input variables */
// do stuff here

Answers (1)

Fred Smith
Fred Smith on 20 Apr 2015
Instead of'sfun')
you probably meant'matlab')
in the latest release. In older releases you would have used
That said, even after you make this change, your invocation still will not work:
Pts_out = coder.ceval('MLSsubroutine_C',Pts_in, Pts_ctrl_in, Pts_ctrl_out, 2, D_hnd_mesh);
coder.ceval is expecting a C call that works with the raw data and not with mxArrays.
You can resolve this in two ways. Refactor your C code into a kernel that does not use mxArrays and a wrapper that converts from mxArrays to raw data, and then call the kernel using coder.ceval. Alternatively, you can write a raw function wrapper that creates mxArrays from the raw data and then calls mexFunction. If both seem equally easy to you, the former is clearly to be preferred.
Good luck,
  1 Comment
Robert on 22 Apr 2015
I hoped it would be possible to directly include that mex function but this seems to be a good solution.
Thank you for this.

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!

Translated by