MATLAB: How to use custom error and print handlers in the compiled C++ shared libraries

MATLAB

I am compiling MATLAB code into a C++ shared library. I want to be able to use my own custom code to handle any display messages (output to STDOUT)

Best Answer

C++ shared libraries compiled using MATLAB support the use of custom print and error handlers. To replace the default handlers, the library needs to be initialized using the following syntax in the driver code (i.e the code calling the DLL functions)
/* Initialize the library liberrorH with custom error and print handlers */
liberrorHInitializeWithHandlers((mclOutputHandlerFcn) myErrorHandler,(mclOutputHandlerFcn) myPrintHandler))
Both these handlers should adhere to the following templates:
static int myPrintHandler(const char *s){
//Please use the mclWrite function for R2006a and later
//mclWrite(1 /* stdout */,"*Print handler called with ",sizeof(char)*strlen("*Print handler called with "));
//mclWrite(1 /* stdout */, s, sizeof(char)*strlen(s));
//Please comment the above two lines and use the one below for R14SP3
std::cout<<"*Print handler called with "<<s<<std::endl;
return 5;
}
See the attached files for a complete example.
Description of the files:
  • testerrorhandling.m: Source MATLAB file being compiled. Has a numeric input based on which it creates various calls to the print and error handlers.
  • cmds.txt: Commands used to generate the DLL file (test with Microsoft Visual C/C++ 6.0)
  • errhndlrDriver.cpp: C++ driver code to call the testerrorhandling from the compiled DLL, creates custom print and error handlers.
  • errmsgchk.m: MATLAB file to run the created executable with different arguments
  • Outputs.txt: Expected output