在C

时间:2017-05-03 19:47:35

标签: c windows windows-console win64

首先,我不是Windows程序员(甚至不是Windows用户),我在Linux上使用交叉编译器来构建Win32和Win64。在挖掘网络(甚至在这里提出问题)后,我设法将一个代码片段放在一起,可以打开一个Windows控制台,并将它用于stdin / stdout / stderr。它适用于Win32,但程序在Win64上崩溃。我猜问题是不同的长整数数据类型大小,gcc甚至警告过这一点。但是,由于我不知道某些Windows API类型的确切用途和大小,因此我无法弄清楚应该更改的内容。当然,最好的是一些win32 / win64独立解决方案。我也尝试使用" HANDLE"为lStdHandle键入,但它甚至不编译。任何人都可以帮忙解决这个问题吗?

    int hConHandle;
    long lStdHandle;
    //HANDLE lStdHandle;
    CONSOLE_SCREEN_BUFFER_INFO coninfo;
    FILE *fp;
    FreeConsole(); // be sure to release possible already allocated console
    if (!AllocConsole()) {
            ERROR_WINDOW("Cannot allocate windows console!");
            return;
    }
    SetConsoleTitle("My Nice Console");
    // set the screen buffer to be big enough to let us scroll text
    GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &coninfo);
    coninfo.dwSize.Y = 1024;
    //coninfo.dwSize.X = 100;
    SetConsoleScreenBufferSize(GetStdHandle(STD_OUTPUT_HANDLE), coninfo.dwSize);
    // redirect unbuffered STDOUT to the console
    lStdHandle = (long)GetStdHandle(STD_OUTPUT_HANDLE);
    hConHandle = _open_osfhandle(lStdHandle, _O_TEXT);
    fp = _fdopen( hConHandle, "w" );
    *stdout = *fp;
    setvbuf( stdout, NULL, _IONBF, 0 );
    // redirect unbuffered STDIN to the console
    lStdHandle = (long)GetStdHandle(STD_INPUT_HANDLE);
    hConHandle = _open_osfhandle(lStdHandle, _O_TEXT);
    fp = _fdopen( hConHandle, "r" );
    *stdin = *fp;
    setvbuf( stdin, NULL, _IONBF, 0 );
    // redirect unbuffered STDERR to the console
    lStdHandle = (long)GetStdHandle(STD_ERROR_HANDLE);
    hConHandle = _open_osfhandle(lStdHandle, _O_TEXT);
    fp = _fdopen( hConHandle, "w" );
    *stderr = *fp;
    setvbuf( stderr, NULL, _IONBF, 0 );
    // Set Con Attributes
    //SetConsoleTextAttribute(GetStdHandle(STD_ERROR_HANDLE), FOREGROUND_RED | FOREGROUND_INTENSITY);
    SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_GREEN | FOREGROUND_INTENSITY);
    SetConsoleMode(GetStdHandle(STD_OUTPUT_HANDLE), ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
    SetConsoleMode(GetStdHandle(STD_INPUT_HANDLE), ENABLE_ECHO_INPUT | ENABLE_LINE_INPUT);

2 个答案:

答案 0 :(得分:2)

我不确切地知道问题是什么。我没有在Linux上使用MinGW进行构建。如果您没有构建控制台应用程序,它可能与无效的文件描述符有关。在这种情况下,CRT初始化文件描述符以将映射作为无效句柄值处理,并且标准FILE流将初始化为-1 fileno。但是我的代码中没有发现问题。

然而,你的*stdin = *fp hack不是可移植的C.它适用于旧版本的MSVC,也可能适用于msvcrt.dll(由于缺乏更好的选择,MinGW有点可疑)。但是,它不适用于新的通用CRT。新CRT中的FILE定义如下:

typedef struct _iobuf
{
    void* _Placeholder;
} FILE; 

因此,分配给*stdin只会覆盖此_Placeholder指针。内部结构实际如下:

struct __crt_stdio_stream_data
{
    union
    {
        FILE  _public_file;
        char* _ptr;
    };

    char*            _base;
    int              _cnt;
    long             _flags;
    long             _file;
    int              _charbuf;
    int              _bufsiz;
    char*            _tmpfname;
    CRITICAL_SECTION _lock;
};

所以你真正覆盖的就是它的缓冲区_ptr

可移植地重新打开标准流的方法是通过freopen。所以我所做的,但也许其他人有更好的解决方案,是freopen NUL设备,如果它是非控制台应用程序,它会将流重置为有效的文件描述符。然后使用_dup2重定向底层文件描述符。例如:

#include <io.h>
#include <stdio.h>
#include <fcntl.h>
#include <Windows.h>

int wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
             LPWSTR lpCmdLine, int nCmdShow)
//int wmain(int argc, wchar_t **argv)
{
    int fdStd;
    HANDLE hStd;
    CONSOLE_SCREEN_BUFFER_INFO coninfo;

    printf("Goodbye, World!\n");

    /* ensure references to current console are flushed and closed
     * before freeing the console. To get things set up in case we're
     * not a console application, first re-open the std streams to
     * NUL with no buffering, and close invalid file descriptors
     * 0, 1, and 2. The std streams will be redirected to the console
     * once it's created. */

    if (_get_osfhandle(0) < 0)
        _close(0);
    freopen("//./NUL", "r", stdin);
    setvbuf(stdin, NULL, _IONBF, 0);
    if (_get_osfhandle(1) < 0)
        _close(1);
    freopen("//./NUL", "w", stdout);
    setvbuf(stdout, NULL, _IONBF, 0);
    if (_get_osfhandle(2) < 0)
        _close(2);
    freopen("//./NUL", "w", stderr);
    setvbuf(stderr, NULL, _IONBF, 0);

    FreeConsole();

    if (!AllocConsole()) {
        //ERROR_WINDOW("Cannot allocate windows console!");
        return 1;
    }
    SetConsoleTitle("My Nice Console");

    // set the screen buffer to be big enough to let us scroll text
    GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &coninfo);
    coninfo.dwSize.Y = 1024;
    //coninfo.dwSize.X = 100;
    SetConsoleScreenBufferSize(GetStdHandle(STD_OUTPUT_HANDLE), coninfo.dwSize);

    // redirect unbuffered STDIN to the console
    hStd = GetStdHandle(STD_INPUT_HANDLE);
    fdStd = _open_osfhandle((intptr_t)hStd, _O_TEXT);
    _dup2(fdStd, fileno(stdin));
    SetStdHandle(STD_INPUT_HANDLE, (HANDLE)_get_osfhandle(fileno(stdin)));
    _close(fdStd);

    // redirect unbuffered STDOUT to the console
    hStd = GetStdHandle(STD_OUTPUT_HANDLE);
    fdStd = _open_osfhandle((intptr_t)hStd, _O_TEXT);
    _dup2(fdStd, fileno(stdout));
    SetStdHandle(STD_OUTPUT_HANDLE, (HANDLE)_get_osfhandle(fileno(stdout)));
    _close(fdStd);

    // redirect unbuffered STDERR to the console
    hStd = GetStdHandle(STD_ERROR_HANDLE);
    fdStd = _open_osfhandle((intptr_t)hStd, _O_TEXT);
    _dup2(fdStd, fileno(stderr));
    SetStdHandle(STD_ERROR_HANDLE, (HANDLE)_get_osfhandle(fileno(stderr)));
    _close(fdStd);

    // Set Con Attributes
    SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),
        FOREGROUND_GREEN | FOREGROUND_INTENSITY);
    SetConsoleMode(GetStdHandle(STD_OUTPUT_HANDLE),
        ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
    SetConsoleMode(GetStdHandle(STD_INPUT_HANDLE),
        ENABLE_ECHO_INPUT | ENABLE_LINE_INPUT);

    printf("Hello, World!\n");

    Sleep(10000);
    return 0;
}

答案 1 :(得分:1)

这是一个句柄,因此您应该使用HANDLE类型。当您致电INT_PTR时,使用SIZE_T转换为_open_osfhandle(或long,如果您的SDK真的已过时),可以截断该值!