"Matt" <th**********@xxyyyzzzz.com> wrote in message
news:Id*****************@news01.roc.ny...
I am trying to cast an ostream reference to void* and back again. The code
below shows the problem isolated from a more complex program. It compiles
quietly but seg faults upon execution.
// ================================================== =================
#include <iostream>
using namespace std;
void myprint(void *s) {
(ostream&)s << "hello, world" << endl;
}
int main(int argc, char *argv[]){
myprint((void *)cerr);
}
// ================================================== =================
Why can't I cast the ostream reference to and from void*?
That's because cerr isn't a pointer in the first place. You're taking an
instance, converting it to a pointer, then trying to convert it to a
reference. As soon as you convert it to a pointer you loose everything. So
try taking the pointer to cerr instead.
This works for me (although I wouldn't do this, this just shows you how to
do what you're trying to do)
#include <iostream>
void myprint(void *s)
{
*((std::ostream*) s) << "hello, world" << std::endl;
}
int main(int argc, char *argv[])
{
myprint((void *)&std::cerr);
}