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 17 // Class to implement "cout" for mex files to print to the matlab terminal 18 // window. 19 // 20 // Insert at the beginning of mexFunction(): 21 // MexStream mout; 22 // std::streambuf *outbuf = std::cout.rdbuf(&mout); 23 // ... 24 // ALWAYS restore original buffer to avoid memory leak problems in matlab 25 // std::cout.rdbuf(outbuf); 26 // 27 class MexStream : public std::streambuf 28 { 29 public: 30 protected: 31 inline virtual std::streamsize xsputn(const char *s, std::streamsize n); 32 inline virtual int overflow(int c = EOF); 33 }; 34 } 35 } 36 37 // Implementation 38 #include <mex.h> xsputn(const char * s,std::streamsize n)39inline 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 overflow(int c)48inline int igl::matlab::MexStream::overflow(int c) 49 { 50 if (c != EOF) { 51 mexPrintf("%.1s",&c); 52 mexEvalString("drawnow;"); // to dump string. 53 } 54 return 1; 55 } 56 #endif 57