473,396 Members | 1,945 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

redefining cout (for using printf/mexprintf)

uli
Hi all!
I'm posting to both newsgroups, because it's actually a C++ problem but
could be that some of you using Matlab-&-MEX-&-C++ was struggling with the
same problem.

I'm trying to rewrite some Matlab routines in C++ for reusing them
identically in Matlab and some other simulation tools. For computational
algebra I want to use the Matrix Template Library (MTL,
http://www.osl.iu.edu/research/mtl/) which is written in C++ and therefore
makes use of std::cout.
I have to use the mexfunction-interface of Matlab to run C++ code within a
Matlab simulation. Since I'm writing my code with MSVC++ 6.0 and running
Matlab on Windows, together with MATLAB and MEX, I can't use "cout" but
"printf" ('cause of the MSWindows specific Matlab-Terminal).
However to come to my Problem now:
To solve this I want to redefine std::cout (within a header of my individual
MEXinterface.cpp) so that it makes use of printf() instead . Could someone
give me some hints or links to information how I could manage this?
I know that it must be tricky since cout prints stream?! So I need to
transform the stream in strings??
Perhaps as a last resort, if it can't be done, any "std::cout << ... "
should print a infomessage.

I know it's not a good way to redefine some functions of the std namespace.
I have never done something like this. But it seems to me to be the only way
out. I also just want to use this redefinition together with Matlab-&-MEX
and probably won't make much use of MTL specific printouts...
thanx a lot of for any kind of help!
regards,
uli
--
For reply remove NOSPAM_ from email-adress

Jul 22 '05 #1
5 6223
"uli" <NO********@nurfuerspam.de> wrote in message news:<c6**********@newssrv.muc.infineon.com>...
Hi all!
I'm posting to both newsgroups, because it's actually a C++ problem but
could be that some of you using Matlab-&-MEX-&-C++ was struggling with the
same problem.

I'm trying to rewrite some Matlab routines in C++ for reusing them
identically in Matlab and some other simulation tools. For computational
algebra I want to use the Matrix Template Library (MTL,
http://www.osl.iu.edu/research/mtl/) which is written in C++ and therefore
makes use of std::cout.
I have to use the mexfunction-interface of Matlab to run C++ code within a
Matlab simulation. Since I'm writing my code with MSVC++ 6.0 and running
Matlab on Windows, together with MATLAB and MEX, I can't use "cout" but
"printf" ('cause of the MSWindows specific Matlab-Terminal).
However to come to my Problem now:
To solve this I want to redefine std::cout (within a header of my individual
MEXinterface.cpp) so that it makes use of printf() instead . Could someone
give me some hints or links to information how I could manage this?


Sure, it's not very complex. Inside std::cout, there is something called
a streambuf. The default streambuf is responsible for writing the
already formatted text to the console (formatting was done by the
std::cout object itself). If you want to send the text to a different
destination, you will have to replace the streambuf. E.g. if you
want to redirect std::cout to a file, open a std::ofstream, and swap
the streambufs. If you have another destination, derive your
custom sterambuf from std::streambuf and implement the applicable
virtual functions.
Pointer: std::stream::rdbuf(std::streambuf*).

Regards,
Michiel Salters
Jul 22 '05 #2
"uli" <NO********@nurfuerspam.de> wrote:
To solve this I want to redefine std::cout (within a header of my individual
MEXinterface.cpp) so that it makes use of printf() instead . Could someone
give me some hints or links to information how I could manage this?
You should not try to "redefine std::cout". What you can do is to replace
the stream buffer used by 'std::cout' with a stream buffer writing to a
new destination, eg. to 'printf()' (although the destinations of 'printf()
and 'std::cout' should actually be identical).
I know that it must be tricky since cout prints stream?! So I need to
transform the stream in strings??


Streams write the chars to stream buffers. These collect the chars in a
buffer which can then be easily handed to whatever function you want to
use. This is the way I would go, anyway.
--
<mailto:di***********@yahoo.com> <http://www.dietmar-kuehl.de/>
<http://www.contendix.com> - Software Development & Consulting
Jul 22 '05 #3
uli
"Dietmar Kuehl" <di***********@yahoo.com> wrote in message
"uli" <NO********@nurfuerspam.de> wrote:
To solve this I want to redefine std::cout (within a header of my individual MEXinterface.cpp) so that it makes use of printf() instead . Could someone give me some hints or links to information how I could manage this?


You should not try to "redefine std::cout". What you can do is to replace
the stream buffer used by 'std::cout' with a stream buffer writing to a
new destination, eg. to 'printf()' (although the destinations of 'printf()
and 'std::cout' should actually be identical).
I know that it must be tricky since cout prints stream?! So I need to
transform the stream in strings??


Streams write the chars to stream buffers. These collect the chars in a
buffer which can then be easily handed to whatever function you want to
use. This is the way I would go, anyway.

Ok, I tried to figure it out with my STL literature. But it seems, that I'am
not really good in C++!
I now know to redirect cout to a file with:
#include <fstream.h>
filebuf *pBuf = new filebuf;
pBuf->open("cout.txt", ios::out);
cout = pBuf;

// ... more code

delete cout.rdbuf();

But for redirecting it to another function how can I change the streambuf*
to 'string' then, like:
#include <iostream>
std::streambuf* str_buf = std::cout.rdbuf();
printf("%s", *str_buf); //<<< doesn't work of course!
thanx, once again!
uli
Jul 22 '05 #4
uli wrote:
Ok, I tried to figure it out with my STL literature.
STL literature would not cover anything related to streams (with the
exception of the various stream iterators) since streams are not part
of the STL: the STL is a library which essentially became the
functional, algorithms, iterators, and containers library of the
standard C++ library. That is STL != standard C++ library.
But for redirecting it to another function how can I change the streambuf*
to 'string' then, like:


Well, this is not exactly what you probably want to do but you could
use a 'std::stringbuf' at first:

#include <iostream>
#include <sstream>
int main() {
std::streambuf* cout_sbuf = std::cout.rdbuf();
std::stringbuf sbuf;
std::cout.rdbuf(&sbuf);
// ...
printf("stream contents: %s\n", sbuf.str().c_str());
std::cout.rdbuf(cout_sbuf);
}

It is relatively important that you restore the original stream buffer
into the stream because after exiting 'main()' the standard stream
objects may be flushed (due to the behavior of the destructor of
'std::ios_base::Init'). Since the installed stream buffer is destructed
by then, this would result in a crash during program termination which
is generally not the best behavior and may even cause havoc on some of
the data which is not yet flushed.

However, I was actually not refering to installing one of the existing
stream buffers since these don't really do the right thing. You want
to create your own stream buffer by deriving from 'std::streambuf' and
overriding the 'overflow()' and 'sync()' methods. The tricky part in
your particular setup is that you apparently have two routes to write
output:
- you might use 'std::cout' to write output
- you might use the underlying mechanism directly to write output
In situations like this you get synchronization problems if you are
not careful and do buffering in the stream buffer. On the other hand,
using an unbuffered stream buffer is likely to cause a performance
problem. You might compromise on setting the 'unitbuf' flag which will
flush the stream after every insertion operation. Another alternative
is to terminate all uses of 'std::cout' with 'std::endl' or 'std::flush'
(the difference between these two is that the former adds a newline
prior to the flush; in general, I recommend against use of 'std::endl'
because it mixes two entirely separate issues but sometimes it just has
the right semantics...).

A simple stream buffer for your purpose would look something like this:

struct printfbuf: std::streambuf {
enum { s_size = 1024 };
printfbuf() { setp(m_buffer, m_buffer + s_size - 2); }
private:
int_type overflow(int_type c) {
if (!traits_type::eq_int_type(c, traits_type::eof()) {
*pptr() = traits_type::to_char_type(c);
pbump(1);
}
return sync() != -1? traits_type::not_eof(c): traits_type::eof();
}
int sync() {
*pptr() = 0;
printf(pbase());
setp(m_buffer, m_buffer + s_size - 2);
return 0;
}
char m_buffer[s_size];
};

This code is not tested (not even compiled) and I guess I forgot
something important. However, to find out more about implementing
stream buffers, you can have a look at various resources:
- Nicolai Josuttis' book "The C++ Standard Library" (Addison-Wesley)
describes this stuff (actually, I have translated/rewritten this
section)
- Angelika Langer and Klaus Kreft's book "C++ IOStreams and Locales"
(Addison-Wesley) covers this stuff in depth
- I have written loads of articles in newsgroup (use eg.
<http://group.google.com/> to locate past articles)
--
<mailto:di***********@yahoo.com> <http://www.dietmar-kuehl.de/>
<http://www.contendix.com> - Software Development & Consulting
Jul 22 '05 #5
"uli" <NO********@nurfuerspam.de> wrote in message news:<c6**********@newssrv.muc.infineon.com>...
"Dietmar Kuehl" <di***********@yahoo.com> wrote in message
"uli" <NO********@nurfuerspam.de> wrote:
To solve this I want to redefine std::cout (within a header of my individual MEXinterface.cpp) so that it makes use of printf() instead . Could someone give me some hints or links to information how I could manage this?
You should not try to "redefine std::cout". What you can do is to replace
the stream buffer used by 'std::cout' with a stream buffer writing to a
new destination, eg. to 'printf()' (although the destinations of 'printf()
and 'std::cout' should actually be identical).
I know that it must be tricky since cout prints stream?! So I need to
transform the stream in strings??


Streams write the chars to stream buffers. These collect the chars in a
buffer which can then be easily handed to whatever function you want to
use. This is the way I would go, anyway.

Ok, I tried to figure it out with my STL literature. But it seems, that I'am
not really good in C++!
I now know to redirect cout to a file with:
#include <fstream.h>
filebuf *pBuf = new filebuf;
pBuf->open("cout.txt", ios::out);
cout = pBuf;

// ... more code

delete cout.rdbuf();

But for redirecting it to another function how can I change the streambuf*
to 'string' then, like:
#include <iostream>
std::streambuf* str_buf = std::cout.rdbuf();
printf("%s", *str_buf); //<<< doesn't work of course!

Try stringstream for in core formatted output:

ostringstream sout ;

sout << "stuff to write out" << endl ;

..
..
..
mexprintf("%s", sout.c_str()) ;

Jack Walker

thanx, once again!
uli

Jul 22 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
by: cylin | last post by:
Dear all, To do below is too long. cout << "Name: " << name << ", Age: " << age << endl; Can cout use "%" to implement? Thanks. cylin.
12
by: Minti | last post by:
Is std::cout slower than printf When we call printf e.g. in printf(20 format conversion specifications, 20 arguments); Is it faster than the std::cout << { 20 redirections to the output...
4
by: Mastupristi | last post by:
I have an array of char for example: char tag = {1, 'W', 0xFF, 0xFF}; I want to obtain: 01 57 FF FF if I try with:
5
by: Ashish Sharma | last post by:
#include <iostream.h> #include <stdio.h> void main() { cout<<"hello"; printf("hi"); }
9
by: liaoo | last post by:
Dear all, I have a question about using cout<<... In standard C, I can use printf("%x",...) to print "hex" number. But in Watcom C++, when using cout<<, I got the "decimal" representation ! ...
25
by: Podrzut_z_Laweczki | last post by:
Hello, I have question (or 2 :)). Is that true that for a large data using scanf/printf instead of cin/cout makes that the program runs faster? And if it is, is it legal to mix scanf/printf with...
12
by: pai | last post by:
Hi, This is a code . the output will be why is this so. Can any nody explain me this.. 4444 2222 7777 8888 aaaa *******************************
10
by: laikon | last post by:
Hello, everyone: this is about overflow in C and C++. int c = 400; printf("%c", c); it print ? on screen, and ascii of '?' is 63.
6
by: rahulsengupta895 | last post by:
. #define MIN(a,b) (a<b?a:b) #define MAX(a,b) (a>b?a:b) #include "Video.h" #define NO_HUE -1
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.