Mex file crash after second run.
4 次查看(过去 30 天)
显示 更早的评论
Hi there,
I just wrote my first mex file and am finding my matlab crashes the second time I try to run my compiled mex file. The only way I can overcome this issue is by closing matlab and reopening it before I run the mex file again. I would most appreciate it if someone could please help me overcome this issue.
Info on code: This file was made to pass in a 3D image volume from matlab, convert the image vector back into a 3D matrix after it is passed into the mex file, and then output the image as a vector after I have processed the data. Below I have my script that I use to load the 3D mri test data set from matlab, compile a mex file, and run the mex file and the actual .cpp file I created. Just note the mri volume dimension was converted from a 4D matrix into a (128 X 128 X 27) matrix and they were hard coded into my code. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Script File:
clear all close all clc
load mri I(:,:,:) = double(D(:,:,1,:));
mex Image.cpp
s = Image(I);
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { mwSize r,c, i,j,k, n; mwSize Ndims; const mwSize *dims;
dims = mxGetDimensions(prhs[0]);
Ndims = mxGetNumberOfDimensions(prhs[0]);
/* get size of the matrix */
r = mxGetM(prhs[0]);
c = mxGetN(prhs[0]);
double *input;
double output[128*128*27];
double temp[128][128][27];
/* get pointer to data */
input = mxGetPr(prhs[0]);
/* access matrix using row/column indices */
mwSize count = 0;
for (i=0; i<128; i++) {
for (j=0; j<128; j++) {
for (k=0; k<27; k++) {
temp[i][j][k] = input[count] * input[count];
count++;
}
}
}
count = 0;
for (i=0; i<128; i++) {
for (j=0; j<128; j++) {
for (k=0; k<27; k++) {
output[count] = temp[i][j][k];
count++;
}
}
}
/* Create a matrix for the return argument */
plhs[0] = mxCreateNumericArray(Ndims,dims,mxDOUBLE_CLASS,mxREAL);
mxSetPr(plhs[0], output);
return;
}
0 个评论
采纳的回答
Titus Edelhofer
2012-1-11
Hi Jon,
the problem is, you use the temporary memory of output in mxSetPr. mxSetPr does not copy but only set's the pointer. At the end of your mex function the variable output is destroyed (and therefore the data of plhs[0] as well!).
What you have to do: move the mxCreateNumericArray before the loops, and use mxGetPr to retrieve output pointer. Then fill up the entries.
Titus
0 个评论
更多回答(2 个)
Jon
2012-1-11
1 个评论
Titus Edelhofer
2012-1-11
Good to hear. You might want to remove the mxSetPr call (it's unnecessary). It doesn't hurt but will confuse the reader ...
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Resizing and Reshaping Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!