Search code examples
cmatlabmex

Returning C struct through mex-function


I am trying to return a struct created in mex function to matlab. Now there is a function mxCreateStructArray but I am creating a node-type structure for a tree data structure and thus it is a recursive linked list formed. Also, the nodes are formed by dynamic memory allocation. So, it is not possible for me to preallocate the memory. I am at a loss as to how I can transport this struct formed to matlab-type struct as output of the function.


Solution

  • If you were working in strictly C, the solution would be to use pointers. Pointers allow you to tell your program "Hey, I'm going to pass you this memory address, I tell you what this address is, and you do stuff for me without you having to work on it by yourself". When pointers are used in this regard, they can be quite powerful, capable of changing the values of constants. However this power is often abused or misused, so many languages put restrictions on the use of pointers, or create their own workarounds to implement their capabilities.

    MATLAB does have some pointer functionality, however your approach to returning the entire tree is bad practice. That much information, let alone efficiency of that is dangerous in more ways than one. A function that returns the entire tree of nodes can be useless or even unnecessary information. You should try redesigning your program such that its starting from the head node, recursively going down the tree and returning each node from tail up.