mexStream.h 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. // This file is part of libigl, a simple c++ geometry processing library.
  2. //
  3. // Copyright (C) 2013 Alec Jacobson <alecjacobson@gmail.com>
  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_MEX_STREAM_H
  9. #define IGL_MEX_STREAM_H
  10. #include <iostream>
  11. namespace igl
  12. {
  13. // http://stackoverflow.com/a/249008/148668
  14. // Class to implement "cout" for mex files to print to the matlab terminal
  15. // window.
  16. //
  17. // Insert at the beginning of mexFunction():
  18. // MexStream mout;
  19. // std::streambuf *outbuf = std::cout.rdbuf(&mout);
  20. // ...
  21. // ALWAYS restore original buffer to avoid memory leak problems in matlab
  22. // std::cout.rdbuf(outbuf);
  23. //
  24. class MexStream : public std::streambuf
  25. {
  26. public:
  27. protected:
  28. inline virtual std::streamsize xsputn(const char *s, std::streamsize n);
  29. inline virtual int overflow(int c = EOF);
  30. };
  31. }
  32. // Implementation
  33. inline std::streamsize igl::MexStream::xsputn(
  34. const char *s,
  35. std::streamsize n)
  36. {
  37. mexPrintf("%.*s",n,s);
  38. mexEvalString("drawnow;"); // to dump string.
  39. return n;
  40. }
  41. inline int igl::MexStream::overflow(int c)
  42. {
  43. if (c != EOF) {
  44. mexPrintf("%.1s",&c);
  45. mexEvalString("drawnow;"); // to dump string.
  46. }
  47. return 1;
  48. }
  49. #endif