3

I'm trying to wrap existing C++ code into a MATLAB callable function. I'm using Visual Studio 2013 to generate the MEX file . The MEX file is created properly, I can call it from MATLAB and pass arguments back and forth without any issues.

Now I want to debug my C++ logic, and I can't seem to get it to work. I've created an m script that calls my function, and had Visual Studio run MATLAB when debugging - as explained here .

When I hit F5 to debug my MEX file, Visual Studio runs MATLAB, and then exits debug mode very quickly, as if the MATLAB process terminated. A few seconds after that, MATLAB starts running the code. It is as if the MATLAB instance I'm running starts another instance and terminates, confusing Visual Studio.

How can I debug my MEX function?

UPDATE: Apparantly MATLAB is doing exactly that, as described here. Adding the -wait argument makes Visual Studio wait until the script is done running, but the breakpoints I set don't work - because the process being debugged is not the process loading the DLL.

Community
  • 1
  • 1
zmbq
  • 38,013
  • 14
  • 101
  • 171

2 Answers2

3

Turns out <MATLABROOT>\bin\matlab.exe actually runs <MATLABROOT>\bin\w64\matlab.exe. So if I ask Visual Studio to run that, breakpoints are triggered as expected.

Running MATLAB this way under the debugger is a lot slower than any other way, but at least now I can debug my code.

zmbq
  • 38,013
  • 14
  • 101
  • 171
  • Can you explain in more detail? I have compiled mex file with -O option so that it created .pdf file. I start Matlab (stop at breakpoint), attach to Matlab process in Visual Studio 2012 (the same which is used by Matlab), run Matlab but it doesnt hit. ANy help would be really appreciated – rank1 Jan 06 '16 at 23:02
  • "MATLABROOT>\bin\ **win64** \matlab.exe" on my machine – Tyson Hilmer Dec 13 '18 at 10:26
2

You could also run a MATLAB session as usual, and then attach Visual Studio to the running process. This is explained in more details in the documentation. Here is a quick summary:

  • compile the source MEX-file with debugging symbols enabled.
  • open the source C/C++ file in Visual Studio, and place a breakpoint.
  • start a normal MATLAB session. Then from Visual Studio, attach to the running matlab.exe process.
  • finally from MATLAB, run the MEX-function. You should hit the breakpoint with execution paused.
Amro
  • 123,847
  • 25
  • 243
  • 454
  • Yes, but that would make debugging again, after fixing the code, more involving - I'd have to unload the DLL from MATLAB, reload it and run the code again. – zmbq Nov 05 '14 at 11:21
  • 4
    fair point, I'm often annoyed by that as well. Sometimes even after unloading MEX-functions (`clear mex`), the symbol files *.PDB would still be locked by the MATLAB process, forcing me to restart MATLAB... – Amro Nov 05 '14 at 16:09