embedded: redirecting stdout (kludge!)
Warren Postma
embed at geocities.com
Thu Mar 2 14:54:52 EST 2000
Here's a way to actually hack my C stdout before running Py_Initialize so I
can capture the output of Py_Initialize.
This sample does the unthinkable and actually overwrites the contents of the
FILE structure that stdout points to. On my platform (visual C++) stdout is
a macro that refers to an array _iob as follows:
#define stdin (&_iob[0])
#define stdout (&_iob[1])
#define stderr (&_iob[2])
This means that you can't just reassign stdin as it was declared as "FILE
*stdin", as it's not a valid l-value, so you can only decide to overwite the
destination structure, and then replace it deftly, hopefully without the
runtime library noticing such a nasty trick.
An fflush() call is mandatory before you pull the reverse-switcheroo.
Other than being a horrible C hack, would this be a preferable way to
redirect Python's stdout if I need a redirection of the errors during
Py_Initialize to be saved?
Any opinions on this Kludge? I wish there was a
Py_RedirectStdout_Before_Py_Initialize(...) call I could use instead.
Warren Postma
--
#include <stdio.h>
int main(int argc, char *argv[])
{
FILE stdout_old, *x;
memcpy(&stdout_old,stdout,sizeof(FILE));
x = fopen("c:\\test.txt","w");
memcpy(stdout,x,sizeof(FILE));
printf("This is a terribly hackish way to redirect stdout\n");
fflush(stdout);
memcpy(stdout,&stdout_old,sizeof(FILE));
fclose(x);
};
More information about the Python-list
mailing list