MexStream.h 1.5 KB

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