Home > Software design >  Do I need to Allocate Memory when using mexGetVariable?
Do I need to Allocate Memory when using mexGetVariable?

Time:03-29

I am getting a variable form my MATLAB workspace via an mexGetVariable. From what I understand, a copy of the variable is made and its pointer is returned when using mexGetVariable.

Would I have to do any memory allocation for this copy?

CodePudding user response:

No, you do not have to do any memory allocation manually. The mexGetVariable( ) routine will allocate all necessary memory for you in the background. The status of this mxArray variable and associated memory are "temporary", meaning the automatic garbage collection inherent in all mex routines will free the memory once the mex routine returns control to the caller unless you have done something to make it persistent (like assign it to one of the plhs[ ] variables). That being said, it is good programming practice to free it manually with mxDestroyArray( ) when you are done with it.

If you don't intend to alter the variable inside your mex routine, it would be faster to use mexGetVariablePtr( ) instead which will avoid making a deep copy of the data.

  • Related