简体   繁体   中英

How can I connect embedded Python to the console's I/O in a Windows GUI app?

I am making a Windows GUI app in C++ in Microsoft Visual Studio 2010. I want to include a Python debug console that can be opened up through the app. I have followed this answer to connect the C++ standard I/O to the console, but when I then embed Python, Python does not seem to be able to access the console through its standard I/O:

create_console(); // essentially the function in the answer I linked to above
Py_Initialize(); // initialize Python
printf("hello, world\n"); // works
PyRun_SimpleString("print \"hello, world\""); // does not work

I tried patching this up with the following:

PyObject *py_stdin = PyFile_FromFile(stdin, "<stdin>", "r", NULL);
PySys_SetObject("stdin", py_stdin);
Py_DECREF(py_stdin); py_stdin = NULL;

PyObject *py_stdout = PyFile_FromFile(stdout, "<stdout>", "w", NULL); // *
PySys_SetObject("stdout", py_stdout);
Py_DECREF(py_stdout); py_stdout = NULL;

PyObject *py_stderr = PyFile_FromFile(stderr, "<stderr>", "w", NULL); // *
PySys_SetObject("stderr", py_stderr);
Py_DECREF(py_stderr); py_stderr = NULL;

But not only do the lines marked with an asterisk (*) above cause a runtime error (the error message is nothing more than "Microsoft Visual Studio C Runtime Library has detected a fatal error in [APP_NAME].exe."), but Python's standard input still does not work, even though the input block above runs without errors.

Your program needs to use the same Microsoft C runtime DLL as was used for the version of Python you're trying to embed. Python 2.7 is compiled with Visual Studio 2008 and uses MSVCRT90.DLL while you're using Visual Studio 2010 and MSVCRT100.DLL . Each DLL has it's own stdin , stdout and stderr , that's why your create_console function has no effect. The two DLLs also have different FILE * stream internal layouts, that's why it crashes when you pass a FILE * stream created using MSVCRT100.DLL to Python. It ends up trying to use it with MSVCRT90.DLL .

Basically to solve this problem you need to compile your application with Visual Studio 2008.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM