简体   繁体   中英

Segmentation Fault using MEX-C function in MATLAB

I'm running a problem while creating a MEX-C function in MATLAB.

Here the thing, I want to return some data generated by my computational routine and put it in plhs[0].

I think I have a misunderstanding using C pointers and MEX files since I'm not really a C guy ...

Here's my code :

void mexFunction(int nlhs, mxArray *plhs[],
                 int nrhs, const mxArray *prhs[])
{
    uint8_t *output_buffer;
    mwSize *size;
    size = (mwSize *) mxGetPr(prhs[0]);
    plhs[0] = mxCreateNumericMatrix(1, size[0], mxUINT8_CLASS, mxREAL);
    output_buffer = (uint8_t *) mxGetData(plhs[0]);
    output_buffer = genData();
}

Basically my function genData() is generating some data and returns it.

I'd like to get the result as an output such that while typing :

a = genData() a would contain the plhs[0] content but that is not working.

I've tried using a mxSetData(plhs[0], output_buffer) . It works but crashes then when doing something else ...

I think the answer should be quite evident but I'm not really an expert in C.

Thank you for your help.

You cannot attach native C/C++ memory to an mxArray via the mxSetData (and friends) API functions. That will screw up the MATLAB Memory Manager and will eventually lead to a crash. You must either alter the genData function to use MATLAB API functions for the the memory allocation (mxMalloc, mxCalloc, etc.) in which case you could then use mxSetData, or you will need to copy the data from the genData returned pointer into the mxArray. Also, your method of getting the size variable is not robust. If the type of integer stored in prhs[0] does not match mwSize then you will either get a wrong answer or crash. So instead of this

mwSize *size;
size = (mwSize *) mxGetPr(prhs[0]);
plhs[0] = mxCreateNumericMatrix(1, size[0], mxUINT8_CLASS, mxREAL);

you should do something like this

mwSize size;
size = mxGetScalar(prhs[0]);
plhs[0] = mxCreateNumericMatrix(1, size, mxUINT8_CLASS, mxREAL);

Finally, you should put in some checks up front to make sure there is a prhs[0] being passed in, that it is numeric, and that it is not empty and not complex, etc. As an aside, the following line dos not attach a pointer to the mxArray:

output_buffer = genData();

It simply overwrites the value in the output_buffer variable ... nothing else.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM