How to "free" or "destroy" pointer array of mxArray?

3 visualizzazioni (ultimi 30 giorni)
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);

Risposta accettata

James Tursa
James Tursa il 16 Feb 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 Commenti
James Tursa
James Tursa il 17 Feb 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
wei zhang
wei zhang il 22 Feb 2021
Thank you. The nested pointer works well.

Accedi per commentare.

Più risposte (0)

Categorie

Scopri di più su MATLAB Compiler in Help Center e File Exchange

Prodotti


Release

R2020b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by