Matlab eventually crashes on Mex function
显示 更早的评论
I have a Mex function that forwards specific messages and message types (1,2,3) from C to the Matlab function 'fruit_getpar.m'. This Matlab function 'fruit_getpar.m' extracts parameters from the message string and stores it as variables. The C messages are generated at random instances. The problem: Matlab crashes eventually with generated C messages, althuogh the structure of this message is allways the same.
any clues?
#include "mex.h"
#include "fruit_matlab.h"
#include "string.h"
// Callback function
void fruit_mexCallback(char *message, double message_type)
{
mxArray *lhs[2];
char sType[5];
if (message == NULL || message_type <= 0)
return;
if (strstr(message, "apple") == NULL && strstr(message, "banana") == NULL && strstr(message, "orange") == NULL) {
itoa((int)message_type, sType, 10);
lhs[0] = mxCreateString(message);
lhs[1] = mxCreateString(sType);
mexCallMATLAB(0, NULL, 2, lhs, "fruit_getpar");
mxDestroyArray(lhs[0]);
mxDestroyArray(lhs[1]);
}
return;
}
// MEX Gateway
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
//pointer to callback function
void (*cbPtr)() = NULL;
cbPtr = fruit_mexCallback;
Register_Callback(cbPtr);
}
regards, Daan
回答(1 个)
James Tursa
2018-5-15
Are you sure that message is null terminated, and that sType is large enough? What happens if you do this:
char sType[33];
2 个评论
DvS
2018-5-16
James Tursa
2018-5-16
编辑:James Tursa
2018-5-16
No. If the only thing being passed is the pointer, then the function has to assume that either the pointer is NULL, or if the pointer is not NULL then it contains a null terminated string. It is up to the caller to do this to ensure that the called function does not access invalid memory.
What is the point of these lines?
void (*cbPtr)() = NULL;
cbPtr = fruit_mexCallback;
Why can't you just pass in fruit_mexCallback to your Register_Callback function?
类别
在 帮助中心 和 File Exchange 中查找有关 Write C Functions Callable from MATLAB (MEX Files) 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!