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

조회 수: 4 (최근 30일)
wei zhang
wei zhang 2021년 2월 16일
댓글: wei zhang 2021년 2월 22일
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);

채택된 답변

James Tursa
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
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
wei zhang
wei zhang 2021년 2월 22일
Thank you. The nested pointer works well.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 MATLAB Compiler에 대해 자세히 알아보기

제품


릴리스

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by