Persistent Object in mex-File (Segmentation violation)
4 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
Hi!
I'm using Mex-Files to call some C++-Functions in Matlab. Now I need some persistent objects at C++-Side for some efficient computations. I found a quite large thread about this subject here, but I came to the following problem: I've a mex-File which calls the constructor of my object and gives Matlab the pointer to it back. Whenever I call another mex-File,which wants to access to my c++-object via the pointer Matlab crashes. The code is the following:
Grid *grid = new Grid(...);
double *output;
plhs[0] = mxCreateDoubleMatrix(1,1,mxREAL);
output = mxGetPr(plhs[0]);
output[0] = (unsigned int) grid;
//this part is just to test if pointer conversion is correct
printf("Pointer to object: %x, as uint: %f\n", grid, output[0]);
unsigned int t = (unsigned int) output[0];
Grid *grid2 = (Grid *) t;
printf("Pointer to grid2: %x\n", grid2);
grid2->calcSomething(...);
mexPrintf(sout.str().c_str());
This is one mex-File and this works fine. I know the conversion between pointer and double/unsigned int is not very smart, but it (seems to)works.
The other mex-File looks like:
unsigned int pointerValue = mxGetScalar(prhs[0]);
Grid *grid = (Grid*) pointerValue;
grid->calcSomething(...)
The pointer is the same (both integer are the same), as it is in the first mex-File, so there is no problem converting it. But I always get a Segmentation violation. So i guess the wrong memory adress is adressed or some context is missing? Anyone any idea whats going wrong here?
1 Commento
Kaustubha Govind
il 5 Lug 2011
First, even from from a C++ point of view, you are declaring 'grid' as a local variable in mexFunction() - you need to make this a global variable and allocate it only the first time it is called.
Second, you never delete 'grid', causing a memory leak every time you call the first MEX-function - I would recommend using mexAtExit (http://www.mathworks.com/help/techdoc/apiref/mexatexit.html) to register a cleanup function that does this for you.
Risposte (1)
Thomas Lai
il 9 Ago 2012
I have tried a very similar method in trying to get C++ object persistence, and even though I did declare global variables in the shared header files it did not seem to register at all when I try to call it from a seperate mex function. My theory is that mex files just have different workspaces and matlab does not care if they both share the same header file.
1 Commento
Vedere anche
Categorie
Scopri di più su MATLAB Compiler in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!