MATLAB Answers

MATLAB Engine : create and manipulate matrix "view" to memory owned by calling process

4 views (last 30 days)
Matthias Schabel
Matthias Schabel on 25 Jan 2011
I am trying to use MATLAB to interactively debug some C++ code and am trying to figure out how to create an mxArray in the MATLAB workspace without copying memory. So, what I'd like to do is something like this (pseudocode) :
// myprogram.cpp
// 1000x1000 array of 100x100 arrays Array<Array<double,2>,2> array(1000,1000,Array<double,2>(100,100));
Engine *engine = engOpen("");
mxArray *cellArray = mxCreateCellMatrix(1000,1000);
for (int i=0;i<1000;++i) { for (int j=0;j<1000;++j) { mxSetCell(mxGetCell(cellArray,mxCalcSingleSubscript(cellArray...)),&array[i][j]); } }
The key is that I don't want MATLAB to own or copy the data pointed to in &array[i][j]...
Any advice would be most welcome...


Sign in to comment.

Answers (1)

James Tursa
James Tursa on 10 Feb 2011
That will not work. In the first place your cellArray mxArray variable does not exist in the workspace, it exists in your program. In the second place your mxSetCell call is totally messed up since you don't have the correct number and type of arguments. E.g. the first argument is the result of a mxGetCell call on a cell array you just created. This cell array has NULL pointers in the array so the mxGetCell call will return NULL. Then you attempt to use that in a mxSetCell call ... program bomb. And the last argument &array[i][j] isn't even an mxArray * as required. To do what you are attempting would require building an mxArray from scratch, attaching the appropriate pointers from array to the mxArray, and then using mxSetCell with that. But now you are mixing C++ native memory inside an mxArray variable, so this will probably also bomb your program when MATLAB tries to free the memory associated with the mxArray. This can be avoided by meticulously un-attaching your C++ memory from the mxArray prior to allowing MATLAB to destroy the mxArray, but it is definitely walking on thin ice and you really have to know what you are doing to pull it off. But even if all of this was coded correctly, your cellArray variable is still in your program and not in the Engine workspace. The only way to accomplish that that I know of is to copy it there via an engPutVariable call. If you are memory starved and really can't afford the extra copy then I would advise looking into making this a mex function instead of an Engine application. With a mex function you can often work with the mxArray and make MATLAB function calls with it without making an extra copy.


Sign in to comment.


Community Treasure Hunt

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

Start Hunting!

Translated by