필터 지우기
필터 지우기

Mex function issues when executing in matlab

조회 수: 2 (최근 30일)
ryan
ryan 2013년 6월 28일
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.

답변 (3개)

Jan
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.

Walter Roberson
Walter Roberson 2013년 6월 28일
Remember that your entry point to a C++ program needs to be defined with
extern "C" {
....
}

ryan
ryan 2013년 6월 28일
편집: ryan 2013년 6월 28일
Would i put that inside the .def file? Right now this is my .def:
LIBRARY LibName EXPORTS mexFunction
And my mexFunction is set up like so:
void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] ) {
return; }
  댓글 수: 5
Walter Roberson
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
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.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Write C Functions Callable from MATLAB (MEX Files)에 대해 자세히 알아보기

태그

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by