MATLAB: Debug functions inside C/C++ shared library loaded using “loadlibrary”

.pdbc/c++debuglibraryloadlibraryMATLABsharedstudiovisual

How to debug functions inside a C/C++ shared library(which is not compiled from MATLAB) loaded using "loadlibrary"?

Best Answer

It is possible to debug and step into functions after calling the "loadlibrary" from MATLAB. To achieve that make sure you meet all the requirements listed below:
  • You have the source code which was used to compile C/C++ shared library.
  • You have Microsoft Visual Studio installed on you machine.
  • Your Microsoft Visual Studio has the same compiler which is supported by your MATLAB release.
  • The source code used for debugging in Visual Studio and the DLL loaded in MATLAB should be under the same project/solution.
Following are the steps to debug functions inside the C/C++ shared library:
  1. Make sure your Visual Studio generates a ".pdb" file. This file should be under your "Debug" folder where your solution is. To generate this folder and file, your Visual Studio Solution configuration should be set to "Debug" in the configuration properties of the solution.
  2. Open MATLAB.
  3. Open the solution in Visual Studio.
  4. In Visual Studio, Debug-> Attach to Process. Select MATLAB from the list. Note, please make sure to load correct instance of MATLAB if there are multiple instances of MATLAB running on the system.
  5. Set breakpoint in your C++ source code, where you would like to debug.
  6. In MATLAB, browse to the location of the "Debug" folder, which contains the DLL to be loaded.
  7. Load the DLL using the "loadlibrary()" function and make sure the DLL is loaded correctly using "libfunctions()" function. "libfunctions()" should list all the functions inside the library.
  8. Call the function from MATLAB using "calllib()", which should hit the breakpoint set in Step 5.
This would halt the execution and you would be able to debug in Visual Studio with the values passed from MATLAB.