Using stdin/out in a windows application bugs only when compiled to 64bit.
Mike Parker
aldacron at gmail.com
Fri Jun 8 02:44:13 UTC 2018
On Thursday, 7 June 2018 at 19:19:55 UTC, realhet wrote:
> Hi,
>
> The following narrow test program works fine when compiled with
> DMD to 32bit target:
>
> import std.stdio, core.sys.windows.windows, core.runtime;
> extern(Windows) int WinMain(HINSTANCE hInstance, HINSTANCE
> hPrevInstance, LPSTR lpCmdLine, int iCmdShow)
> {
> Runtime.initialize;
> writeln("Hello");
> stdout.flush; //exception
> readln; //exception
> return 0;
> }
>
> It shows the console window and waits for user input at readln.
>
> If I try to compile this to 64bit target or with LDC (both 32
> and 64) it gets privileged instruction exception at
> stdout.flush. If I comment out flush then it fails at readln.
I get no exceptions with this code, but if I run if I compile
with no flags, it prints hello and waits for input. With
-m32mscoff or -m64, there's no output. If I run from Windows
Explorer, the no-flag version pops up a console, prints and
waits, while the -m32mscoff and do nothing.
As Steven mentioned earlier, this is a runtime issue. The
standard I/O streams are not available in the MSVC runtime by
default when compiling as a GUI application. You don't have to
enable any flags to get that -- it's automatic when WinMain is
present. The DititalMars runtime, which is what you get with the
default compile, apparently does initialize the standard I/O
streams and makes sure the console pops up when you write to it.
>
> Is there a way to fix this? I don't wanna lose the console
> window even on 64bit.
>
If you want to keep WinMain and still have the console stuff
available from the start with the MSVC runtime, you can get it
with this:
dmd -m64 -L/SUBSYSTEM:console -L/ENTRY:WinMainCRTStartup foo.d
With this (for -m32mscoff as well), the above code runs the same
as it does with the DigitalMars runtime.
More information about the Digitalmars-d-learn
mailing list