Mex function issues when executing in matlab
2 次查看(过去 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!