C pointers to Matlab variables
Asked Answered
C

1

6

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);
Corneille answered 9/10, 2014 at 19:17 Comment(5)
What good is the ap variable doing? Why not just get the mxArray corresponding to a, and call mxGetPr on that as many times as you like?Gravid
What's the output you are seeing?Diaphoresis
The a data structure could be modified in Matlab between times that the engine accesses it. When a is modified it appears to be copied to a different memory location, so mxGetPr does not point to the updated copy.Corneille
Currently it is outputting a number that isn't what is stored in a, such as a = -128778304.000000.Corneille
What does printf("a = %lf", a); print?Diaphoresis
M
3

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.

Moonmoonbeam answered 9/10, 2014 at 23:18 Comment(1)
think of the MATLAB engine as an abstraction of a client/server model; you certainly cannot directly access remote object's data on the server, you can only do it though the exposed interface and API from the client side.Moonmoonbeam

© 2022 - 2024 — McMap. All rights reserved.