Using Matlab "engine.h" from C ++ correctly

I have code that processes frames in each iteration and generates a matrix. My ultimate goal is to send the matrix data to Matlab to explore the evolution of the matrix with each frame. To do this, I defined the Engine static variable in the header file (helper.h).

#include "engine.h"; #include "mex.h"; static Engine *engine; 

In the main () program, I open the engine only once:

 #include helper.h main(){ if (!(engine = engOpen(NULL))) { MessageBox ((HWND)NULL, (LPSTR)"Can't start MATLAB engine",(LPSTR) "pcTest.cpp", MB_OK); exit(-1);} //here comes frame processing using a while loop . . //a function is called (defined in matrix.cpp) . //frame processing ends } 

And inside matrix.cpp, where I get the matrix that I want to send to the Matlab Engine, so I am doing something like this:

 #include helper.h mxArray *mat; mat = mxCreateDoubleMatrix(13, 13, mxREAL); memcpy(mxGetPr(mat),matrix.data, 13*13*sizeof(double)); engPutVariable(engine, "mat", mat); 

I want to use the pointer to the engine in the most efficient way. I'm a little worried about how to use the Matlab mechanism properly.

Any help is appreciated because the Matlab documentation and examples did not help at all, as they have all the code in a single file and do not use iteration. Thanks in advance.

EDIT

The first problem is resolved with respect to the engine pointer. The solution declares it as extern.

 #include "engine.h"; #include "mex.h"; extern Engine *engine; 

and in main.cpp

 #include helper.h Engine *engine=NULL; main(){} 
+2
source share
1 answer

static means "locally for the current compilation unit". The compiler is usually a single .cpp file, so your program has two engine variables, one in main.o and one in matrix.o . You need to declare the engine as extern in the header file and define it without any modifier in only one .cpp file.

helper.h:

 extern Engine* engine; 

main.cpp:

 #include "helper.h" Engine* engine = NULL; 
+4
source

Source: https://habr.com/ru/post/1390789/


All Articles