Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C pointers to Matlab variables

I'm working on a C program that needs to repeatedly access a large Matlab data structure. This is a graphics intensive program using OpenGL so it has to be fast.

Repeatedly accessing this data structure with Matlab Engine seems to take too long (~ 10-20 ms for each call to engGetVariable and engPutVariable). I think this is because these functions copy the data in memory.

Thus, instead of using engGetVariable on the data structure itself, now I'm trying to get a pointer to the data structure. If I call engGetVariable on the pointer, I could access the data structure in C by dereferencing the pointer, without having to copy the data in memory first. However I have not been able to get this to work so far. Is something like this possible?

// Make vars in matlab workspace
engEvalString(ep, "a=9");
engEvalString(ep, "ap=getPointer(a)");

// Get variables in C
ap = engGetVariable(ep, "ap");
a = *mxGetPr(ap);

printf("a = %f", a);
like image 902
Eric Miller Avatar asked Oct 09 '14 19:10

Eric Miller


1 Answers

MATLAB engine operates by running in the background as a separate process from your program, and has its own address space. Therefore pointers to data in memory of another process is out of the question, and the only option is communicating using some sort of IPC mechanism.

On Windows the Engine API is based on COM interfaces, while on UNIX systems the engine is based on pipes (it can even run against remote machines with the help of rsh).

So the only option you have is to use the exposed functions engGetVariable and engPutVariable to exchange data: You obtain a copy of a variable from the MATLAB workspace using engGetVariable, you get the underlying mxArray data pointer with mxGetData and manipulate the array as you wish, then you send the updated copy back to MATLAB using engPutVariable.

like image 118
Amro Avatar answered Nov 01 '22 08:11

Amro