Mehrdad Nazmdar
Mehrdad Nazmdar

Reputation: 192

How MATLAB mex files access MATLAB instances?

This is the entry point for every mex file:

void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]);

In fact mex files are windows dll files with mexFunction as the main function. My question is when the mex function is called, how it can access matlab instance specific data from inside the mex. As an example, consider 'mexPutVariable' function. It's job is 'copy an array from inside MEX-function into the specified workspace (outside mex)'. But how it knows where is 'workspace'. No parameter has passed to mex (like a pointer), containing matlab instance data (caller). mex files know only nlhs, plhs, nrhs, prhs and none of them can help mex files to excavate matlab instance specific data(caller function information).

Upvotes: 0

Views: 223

Answers (1)

CitizenInsane
CitizenInsane

Reputation: 4855

A possible solution is that "Matlab.exe" is declaring mexPutVariable as an exported function:

[Matlab.exe]

int __declspec(dllexport) mexPutVariable(const char* workspace, const char* name, const mxArray* parray)
{
    ...
}

It is then very easy to retreive this function from the dll using GetModuleHandle and GetProcAddress:

[Module.dll]

// Declare function pointer 
int (*FctnPtr)(const char* workspace, const char* name, const mxArray* parray);

// Retreive the main executable 
HANDLE hExe = GetModuleHandle(NULL);

// Link to exported function in the exe just like you would do for any dll    
FctnPtr mexPutVariable = (FctnPtr)GetProcAddress(hExe, "mexPutVariable");

// Use exported function from the dll
mexPutVariable("Base", "foo", myArray);

For compiling the mex file and after looking at mex.h file, mexPutVariable is declared as an external function to link with:

LIBMWMEX_API_EXTERN_C int mexPutVariable(const char* workspace, const char* name, const mxArray* parray);

Which turn to be simply (when compiled as dll side):

 extern "C" int mexPutVariable(const char* workspace, const char* name, const mxArray* parray);

Upvotes: 1

Related Questions