使用 Visual Studio 2015 编译时,将控制台(或标准输出)重定向到命名管道不再有效

Redirecting console (or stdout) to named pipe no longer works when compiling with Visual Studio 2015

我有一个脚本引擎,可以将其标准输出重定向到命名管道以进行调试。下面的代码自 Visual Studio 6 以来一直有效,但在使用 VS2015 编译时似乎不再有效。不会抛出任何错误,但输出会继续写入控制台而不是命名管道。当我在 VS2012 中编译此应用程序时,它按预期工作。

hNamedPipe 是我要将控制台文本重定向到的管道。

int hCrt = _open_osfhandle((intptr_t)hNamedPipe, _O_TEXT);
FILE *hf = _fdopen(hCrt, "w");
*stdout = *hf;
setvbuf(stdout, NULL, _IONBF, 0);

在使用 Visual C++ v14 平台工具集进行编译时,如何将 stdio 重定向到命名管道?

多亏了 James McNellis,我才得以找到解决方案:

This is by design. FILE is an opaque data type; you are not allowed to dereference a FILE as you have done in your code.

这是最终对我有用的代码:

void main()
{
    HANDLE hNamedPipe = Create_Some_Named_Pipe();

    RedirectIO(stdout, hNamedPipe);
    printf("Hello World."); //This arrived at the listening named pipe.
}

void RedirectIO(FILE *hFrom, HANDLE hTo)
{
    int fd = _open_osfhandle((intptr_t)hTo, _O_WRONLY | _O_TEXT);
    _dup2(fd, _fileno(hFrom));
    setvbuf(hFrom, NULL, _IONBF, 0); //Disable buffering.
}