问题
I have a code that proceses frames in each iteration and generatesa matrix. My final goal is to send the matrix data to matlab in order to examine the evolution of the matrix with each frame. In order to achieve this I defined a static variable Engine in a 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 is where I get the matrix I want to send to Matlab Engine, so I do 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 engine the most efficient way. I am a bit conffused about how to correctly use matlab engine.
Any help woould be welcomed, because the matlab documentation and examples didn't help at all as they have all the code in the same file and they don't use iterations. Thanks in advance.
EDIT
First problem solved about the engine pointer. The solution is declaring it as extern.
#include "engine.h";
#include "mex.h";
extern Engine *engine;
and in main.cpp
#include helper.h
Engine *engine=NULL;
main(){}
回答1:
static
means "local to the current compilation unit". A compilation unit is normally a single .cpp
file, so you have two engine
variables in your program, one in main.o
and one in matrix.o
. You need to declare engine
as extern
in the header file and define it without any modificator in exactly one .cpp
file.
helper.h:
extern Engine* engine;
main.cpp:
#include "helper.h"
Engine* engine = NULL;
来源:https://stackoverflow.com/questions/8838095/using-matlab-engine-h-from-c-correctly