"James Tursa" wrote in message <firstname.lastname@example.org>... > "Xueming " <email@example.com> wrote in message <firstname.lastname@example.org>... > > > Currently I meet exactly the same problem. I wrote a function in C which returns mxArray* to Matlab, and this function is called in a shared library as well, and it will be called continuously. To free memory which occupied by return mxArray I wrote a function ( using mxDestroyArray), however, Matlab crashed, and seems it cannot find the location of returned mxArray. Is that becaues Matlab has it own garbage collection and after every call of function, it frees the memory occupied by returned mxArray? > > Have you figured this issue out? I will appreciate a lot if you can give me any hint:) > > In general, you should *not* be using mxDestroyArray on anything that is being returned to MATLAB. That will invalidate the data in the mxArray and cause MATLAB to crash. > > James Tursa
Hi James, Now I have two issues, 1) I create a C function, which will be called by Matlab, and when everytime it's called, it create a mxArray and return this pointer to Matlab. With called more and more times, it creates more and more mxArray. I guess the memory must be significantly occupied. I'm thinking if we can mxDestory a mxArray (by writing another function) as soon as it's returned to Matlab, so that we only allocate memory for current mxArray.
2)How about inside C code, if declaring a global mxArray*, how to make this global pointer point to a mxArray which is returned by a C function. I tried to declare a global mxArray*, and set it point to a mxArray and returned to Matlab. This global mxArray* is used in other functions. But it seems in other functions, the global mxArray pointer could not be found where it points to. I got some strange result. Could anyone tell me the reason. Here is a simple code. if run this code, calllib('mxArrayTest', 'create'), calllib('mxArrayTest','test'); the result of retruing mxCell1 and mxCell_g are completely different. The free_mxelem(mxCell_g) works pretty well just following mxCell_g=mxCell1, however, outside the "create" function, the free_mxelem() shows pretty strange result. I assume this is because after C returns mxArray to Matlab, memory of mxArray will be free automatically.
here is my code: /////////////////mxArrayTest.c #include "mex.h" /* only needed because of mexFunction below and mexPrintf */ #include <math.h> #include "mxArrayTest.h" #include "string.h"