Skip to content

mpy-cross: Fix output to stdout on Windows. #17879

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions mpy-cross/main.c
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,11 @@
* THE SOFTWARE.
*/

#ifdef _WIN32
#include <fcntl.h>
#include <io.h>
#endif

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
Expand Down Expand Up @@ -92,7 +97,28 @@ static int compile_and_save(const char *file, const char *output_file, const cha

if ((output_file != NULL && strcmp(output_file, "-") == 0) ||
(output_file == NULL && strcmp(file, "-") == 0)) {
// Windows defaults stdout to text mode which will corrupt the MPY
// output. Change it to binary mode to avoid this.
#ifdef _WIN32
fflush(stdout);
_setmode(fileno(stdout), _O_BINARY);

nlr_buf_t nlr2;
if (nlr_push(&nlr2) == 0) {
mp_raw_code_save(&cm, (mp_print_t *)&mp_stdout_print);
nlr_pop();

// Restore the original mode in case we have to print unhandled exceptions
fflush(stdout);
_setmode(fileno(stdout), _O_TEXT);
} else {
fflush(stdout);
_setmode(fileno(stdout), _O_TEXT);
nlr_jump(nlr2.ret_val);
}
#else
mp_raw_code_save(&cm, (mp_print_t *)&mp_stdout_print);
#endif
} else {
vstr_t vstr;
vstr_init(&vstr, 16);
Expand Down
Loading