【问题标题】:Temporarly disabling Console output from a 3rd party dll暂时禁用来自第 3 方 dll 的控制台输出
【发布时间】:2015-08-08 09:19:15
【问题描述】:

我有一个 WIN 32 控制台应用程序,它使用来自我没有源代码的第 3 方 dll 的功能。当从这个特定的 dll 调用导出的函数时,我的控制台充满了源自导出方法的消息。

有什么方法可以禁用第三方 dll 的控制台输出“本地化”?当然,原始 dll“加载器”进程(我的应用程序)必须仍然能够提供控制台输出,因为它被需要解释控制台的客户端脚本工具包作为子进程调用。所以你可以想象,如果我将不受控制的控制台输出传递给这个父进程,事情可能会出错。

我已经尝试过这篇文章的答案: Disable Console Output from External Program (C++) 像这样: system( "3rdparty.dll >nul 2>nul" ); 但它什么也没做。

【问题讨论】:

    标签: c++ console


    【解决方案1】:

    您可以在调用第 3 方库之前将 stdoutstderr 重定向到一个文件,然后再将它们重定向回来。

    你可以这样写一个类:(这是针对 Windows 和 Visual C++ 的。其他更类似于 POSIX 的环境需要稍微不同的代码。)

    class RedirectStandardOutputs {
    private:
        int m_old_stdout, m_old_stderr;
    public:
        RedirectStandardOutputs (char const * stdout_name, char const * stderr_name)
            : m_old_stdout (-1), m_old_stderr (-1)
        {
            fflush (stdout);
            fflush (stderr);
            m_old_stdout = _dup(_fileno(stdout));
            m_old_stderr = _dup(_fileno(stderr));
            freopen (stdout_name, "wb", stdout);
            freopen (stderr_name, "wb", stderr);
        }
    
        ~RedirectStandardOutputs ()
        {
            fflush (stdout);
            fflush (stderr);
            _dup2 (m_old_stdout, _fileno(stdout));
            _dup2 (m_old_stderr, _fileno(stderr));
        }
    };
    

    还请记住,您需要同时包含 <stdio.h><io.h>

    上述类在其构造函数中将stdoutstderr 重定向到普通文件,并在其析构函数中恢复它们。你可以这样使用它:

    // This function writes stuff to the console:
    void Foo (int i)
    {
        printf ("(%d) Hello, world!\n", i);
        fprintf (stderr, "(%d) Hello, again.\n", i);
    }
    
    // ... 
    // Later, you call the Foo() function three times, but only the
    // second one is redirected:
    Foo (0);
    
    {
        RedirectStandardOutputs rso ("x.txt", "y.txt");
        Foo (1);
    }
    
    Foo (2);
    

    请注意,这可能不是很快(特别是在 Windows 上),因此请将其置于对性能敏感的区域之外。

    如果你想禁用写入控制台而不是仅仅将它们重定向到文本文件,你仍然可以使用这种方法,但你必须传入字符串 "NUL" 作为文件名,即:

    RedirectStandardOutputs rso ("NUL", "NUL");
    

    希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-01-09
      • 1970-01-01
      • 1970-01-01
      • 2020-07-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多