Mex function issues when executing in matlab
조회 수: 1 (최근 30일)
이전 댓글 표시
I have created a mex function using visual c++ 2010, and for some reason, the function works but once the function ends, it causes matlab to shut down. my function in c++ is called 'void main()'. I have found some documentation that suggests I rename to 'void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])' but when I try and use that (also fixed in my .def), i get the error 'error LNK2019: unresolved external symbol main referenced in function __tmainCRTStartup'. So i go into link properties under advanced and add in the following: '/ENTRY:mexFunction' but that is causing the error: 'error LNK2001: unresolved external symbol /ENTRY: mexFunction'. What do i do to make this function work correctly w/out shutting down my matlab!?!
Thank you in advanced for any help.
댓글 수: 0
답변 (3개)
Jan
2013년 6월 28일
편집: Jan
2013년 6월 28일
C++ MEX functions do neither require a .def file nor a main() function. The function mexFunction() is called instead, such that a minimal MEX file looks like:
#inlcude "mex.h"
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{ // Some dummy code:
mexPrintf("Number of inputs: %d\n", nrhs);
mexPrintf("Number of outputs: %d\n", nlhs);
}
Save this as "dulltext.cpp" and compile it by mex dulltest.c. No main(), no .def.
This mexFunction can now convert the Matlab arrays of the type mxArray * to the corresponding C-arrays, call the calculation in C as subfunctions, and convert the results back to mxArray * as output to Matlab.
When Matlab shuts down after the execution of your code, the code contains a bug.
댓글 수: 0
Walter Roberson
2013년 6월 28일
Remember that your entry point to a C++ program needs to be defined with
extern "C" {
....
}
댓글 수: 0
ryan
2013년 6월 28일
편집: ryan
2013년 6월 28일
댓글 수: 5
Walter Roberson
2013년 6월 28일
For technical reasons, the real entry point for C programs (and presumably C++ as well) is not main() itself, but rather a routine that runs before main() does. If you were to manage to change your entry point to main then your C++ code would not function properly for buffered I/O or for dynamic memory allocation or for argv and argc.
I would suggest switching to int main instead of void main, and returning 0 from the routine.
Jan
2013년 6월 28일
@Walter: I disagree. Ryan wants to create a MEX-function. Then a main() is not required, neither as void nor as int.
참고 항목
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!