I would like to implement a bidirectional programming interface to MATLAB, to make MATLAB accessible from another programming language. I'd like to be able to:
I'm looking for ways to implement this. Please see the detailed description below.
Point 1. can be solved using the MATLAB Engine interface, but that doesn't allow for callbacks (point 2.).
An alternative solution would be using the MEX interface: language X is running in a separate process and supports a bidirectional communication protocol. I could write a MEX function which will open the communication channel and makes everything possible that one can do with the MATLAB Engine. This MEX function would never return (until MATLAB is closed), it would listen for incoming messages on the communication channel and would use mexPutVariable, mexGetVariable, mexEvalString to evaluate MATLAB code when necessary. It would work just like the MATLAB Engine. All is good so far. But what about callbacks?
First I thought that I could implement a second MEX function which would allow calling back to language X. But for this, I would need access to the data structures related to the communication protocol, which means I would need to be able to share memory with the first MEX function that initiated the connection.
Question 1 Is it possible to share memory between MEX functions? From what I could google up, the answer seems to be no. One possibility that might work would be this: create a C struct which has function pointers to all the functions I need to use. Get a pointer to the struct and store it as an integer in a MATLAB variable. Then from the MEX function retrieve this variable, convert it back to a pointer and access the functions. This might work, but it feels very nasty and I very much want to avoid it.
Instead of using the MEX interface, I could create a shared library, which can hold several functions that can share memory between them. But then I wouldn't have access to the MEX interface (mexEvalString, etc.)
Question 2: Is it possible to access MEX functions form a shared library? Would it be possible to load libmex as a shared library too? I assume that mex* functions need a specific environment in order to work correctly.
Question: What are my options for allowing for callbacks in such a situation?
Any shared library directly or indirectly loaded by MATLAB can use mx and mex functions. To do this they must include the correct headers and link against the correct libraries. The mex compile command takes care of this but it can be done without using the mex command.
MATLABROOT/extern/examples/shrlib/yprime.c is an example of a mex file that has additional exports that can be called with calllib.
Without more information about the language you are trying to support it is difficult to give specific suggestions. Can MATLAB and the other language be loaded into the same process or must two process be used?