How to "free" or "destroy" pointer array of mxArray?
2 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Hi,
I am using mexCallMATLAB in mex. So I need to construct pointer array for multi input or output. Like the below tmp variable. I would like to know how to free it.
mxArray *tmp[3];
mexCallMATLAB(3,tmp,1,A,"find");
% must I do it in this way
mxDestroyArray(tmp[0]);
mxDestroyArray(tmp[1]);
mxDestroyArray(tmp[2]);
% or
mxDestroyArray(tmp);
0 commentaires
Réponse acceptée
James Tursa
le 16 Fév 2021
You must do each one. So
mxDestroyArray(tmp[0]);
mxDestroyArray(tmp[1]);
mxDestroyArray(tmp[2]);
or you could put these in a loop.
Doing this
mxDestroyArray(tmp);
would likely result in a seg fault, since tmp does not point to any dynamically allocated mxArray. In particular, it would definitely not destroy the three mxArrays you want destroyed.
3 commentaires
James Tursa
le 17 Fév 2021
You can't redefine tmp in C/C++. Once it has been defined that is what it is. If you need different sizes of tmp there are two approaches.
1) Make tmp big enough to handle all of your needs. The unused array elements don't hurt you. E.g.,
mxArray *tmp[100]; // make it big enough to hold 100 mxArray pointers
mexCallMATLAB(3,tmp,1,A,"find"); // using only three spots is OK
// use the three spots of tmp here
// then destroy the three spots you used
mxDestroyArray(tmp[0]);
mxDestroyArray(tmp[1]);
mxDestroyArray(tmp[2]);
mexCallMATLAB(5,tmp,1,A,"some_other_function"); // use only five spots here
// use the five spots of tmp here
// then destroy the five spots you used
mxDestroyArray(tmp[0]);
mxDestroyArray(tmp[1]);
mxDestroyArray(tmp[2]);
mxDestroyArray(tmp[3]);
mxDestroyArray(tmp[4]);
2) Make tmp a pointer to pointer to mxArray and allocate it. E.g.,
mxArray **tmp;
tmp = (mxArray **) mxMalloc(3 * sizeof(*tmp)); // allocate space for three spots
mexCallMATLAB(3,tmp,1,A,"find"); // using three spots here
// use the three spots of tmp here
// then destroy the three spots you used
mxDestroyArray(tmp[0]);
mxDestroyArray(tmp[1]);
mxDestroyArray(tmp[2]);
mxFree(tmp); // free the three spots
tmp = (mxArray **) mxMalloc(5 * sizeof(*tmp)); // allocate space for five spots
mexCallMATLAB(5,tmp,1,A,"some_other_function"); // use five spots here
// use the five spots of tmp here
// then destroy the five spots you used
mxDestroyArray(tmp[0]);
mxDestroyArray(tmp[1]);
mxDestroyArray(tmp[2]);
mxDestroyArray(tmp[3]);
mxDestroyArray(tmp[4]);
mxFree(tmp); // free the five spots
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Execution Speed dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!