www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.bugs - [Issue 23312] New: Cannot use writeln with WinMain

https://issues.dlang.org/show_bug.cgi?id=23312

          Issue ID: 23312
           Summary: Cannot use writeln with WinMain
           Product: D
           Version: D2
          Hardware: x86_64
                OS: Windows
            Status: NEW
          Severity: normal
          Priority: P1
         Component: druntime
          Assignee: nobody puremagic.com
          Reporter: alex perry.express

New to D, so maybe I'm doing something stupid here but I can't use writeln when
I'm using win32. Here's a minimal example:

```
import core.runtime;
import core.sys.windows.windows;
import core.sys.windows.winuser;
import std.string;
import std.utf;
import std.stdio;

pragma(lib, "user32");

extern (Windows)
int WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
            LPSTR lpCmdLine, int nCmdShow)
{
    int result;

    try
    {
        Runtime.initialize();
        result = myWinMain(hInstance, hPrevInstance, lpCmdLine, nCmdShow);
        Runtime.terminate();
    }
    catch (Throwable e) 
    {
        MessageBox(null, e.toString().toUTF16z(), null,
                    MB_ICONEXCLAMATION);
        result = 0;     // failed
    }

    return result;
}

int myWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
              LPSTR lpCmdLine, int nCmdShow)
{
    writeln("hello\n");
    return 0;
}
```

It causes a crash in the second `__setmode` of this part in
`LockingTextWriter`:
```
version (MICROSOFT_STDIO)
            {
                // Microsoft doesn't implement fwide. Instead, there's the
                // concept of ANSI/UNICODE mode. fputc doesn't work in UNICODE
                // mode; fputwc has to be used. So that essentially means
                // "wide-oriented" for us.
                immutable int mode = __setmode(f.fileno, _O_TEXT);
                    // Set some arbitrary mode to obtain the previous one.
                __setmode(f.fileno, mode); // Restore previous mode.
                if (mode & (_O_WTEXT | _O_U16TEXT | _O_U8TEXT))
                {
                    orientation_ = 1; // wide
                }
            }
```

I can use `OutputDebugString` instead but I should be able to use writeln
safely right? 

Thanks

--
Aug 29 2022