MATLAB returns empty string from C-MEX file

6 次查看(过去 30 天)
I have an external C function which takes a double pointer and returns a char. The problem is that when I interface that function, I cannot extract the character. Always an empty string is returned by MATLAB. What is the problem? The mex compiler returns no errors and warnings.
Here is a minimum working example:
#include "mex.h"
char mwe(double* a)
{
return 'h';
}
/* Gateway function */
void mexFunction( int nlhs, mxArray *plhs[],
int nrhs, const mxArray *prhs[])
{
char *code;
double *input;
input = mxGetPr(prhs[0]);
*code = mwe(input);
plhs[0] = mxCreateString(code);
}

采纳的回答

James Tursa
James Tursa 2018-11-19
编辑:James Tursa 2018-11-20
It is hard to believe that this code did not crash MATLAB. The issues:
char *code; <-- This is an uninitialized pointer ... it contains a garbage address
double *input;
input = mxGetPr(prhs[0]);
*code = mwe(input); <-- this copies a char into the garbage address (should have crashed MATLAB here)
plhs[0] = mxCreateString(code); <-- Attempts to create a MATLAB char array from the bytes at that garbage address
That mxCreateString( ) call could easily have crashed MATLAB as well. If you want to copy characters into a pointer, then you need to allocate that pointer first. E.g.,
code = mxMalloc(2);
:
code[0] = mwe(input);
code[1] = '\0'; /* Null terminate the string */
:
mxFree(code);
It is not really clear what your ultimate intent is passing a double pointer into mwe and getting a char passed back, so I can't give you any advice there unless you give more details.
  5 个评论
James Tursa
James Tursa 2018-11-22
If you are always only getting a single char back and you want to create an mxArray string from it, I would just avoid that mxMalloc( ) and mxFree( ) stuff entirely. E.g., just do this instead:
char code[2] = {0,0}; /* Includes the null termination */
double *input;
input = mxGetPr(prhs[0]);
code[0] = mwe(input);
plhs[0] = mxCreateString(code);
Zoltán Csáti
Zoltán Csáti 2018-11-22
Yes, the C function I must interface always returns one char. Thanks for the suggestion.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Write C Functions Callable from MATLAB (MEX Files) 的更多信息

标签

产品


版本

R2015b

Community Treasure Hunt

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

Start Hunting!

Translated by