MexStream.h 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. // This file is part of libigl, a simple c++ geometry processing library.
  2. //
  3. // Copyright (C) 2013 Alec Jacobson <[email protected]>
  4. //
  5. // This Source Code Form is subject to the terms of the Mozilla Public License
  6. // v. 2.0. If a copy of the MPL was not distributed with this file, You can
  7. // obtain one at http://mozilla.org/MPL/2.0/.
  8. #ifndef IGL_MATLAB_MEX_STREAM_H
  9. #define IGL_MATLAB_MEX_STREAM_H
  10. #include <iostream>
  11. namespace igl
  12. {
  13. namespace matlab
  14. {
  15. /// Class to implement "cout" for mex files to print to the matlab terminal
  16. /// window.
  17. ///
  18. /// \code{cpp}
  19. /// // very beginning of mexFunction():
  20. /// MexStream mout;
  21. /// std::streambuf *outbuf = std::cout.rdbuf(&mout);
  22. /// ...
  23. /// // ALWAYS restore original buffer to avoid memory leaks in matlab
  24. /// std::cout.rdbuf(outbuf);
  25. /// \encode
  26. ///
  27. /// http://stackoverflow.com/a/249008/148668
  28. class MexStream : public std::streambuf
  29. {
  30. public:
  31. protected:
  32. inline virtual std::streamsize xsputn(const char *s, std::streamsize n);
  33. inline virtual int overflow(int c = EOF);
  34. };
  35. }
  36. }
  37. // Implementation
  38. #include <mex.h>
  39. inline std::streamsize igl::matlab::MexStream::xsputn(
  40. const char *s,
  41. std::streamsize n)
  42. {
  43. mexPrintf("%.*s",n,s);
  44. mexEvalString("drawnow;"); // to dump string.
  45. return n;
  46. }
  47. inline int igl::matlab::MexStream::overflow(int c)
  48. {
  49. if (c != EOF) {
  50. mexPrintf("%.1s",&c);
  51. mexEvalString("drawnow;"); // to dump string.
  52. }
  53. return 1;
  54. }
  55. #endif