How to "free" or "destroy" pointer array of mxArray?
2 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
James Tursa
2021-2-16
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 个评论
James Tursa
2021-2-17
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
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Execution Speed 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!