mexStream.h 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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. #include <mex.h>
  34. inline std::streamsize igl::MexStream::xsputn(
  35. const char *s,
  36. std::streamsize n)
  37. {
  38. mexPrintf("%.*s",n,s);
  39. mexEvalString("drawnow;"); // to dump string.
  40. return n;
  41. }
  42. inline int igl::MexStream::overflow(int c)
  43. {
  44. if (c != EOF) {
  45. mexPrintf("%.1s",&c);
  46. mexEvalString("drawnow;"); // to dump string.
  47. }
  48. return 1;
  49. }
  50. #endif