抑制控制台从导入的DLL打印 [英] Suppress Console prints from imported DLL

查看:59
本文介绍了抑制控制台从导入的DLL打印的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C#控制台应用程序中,我正在导入本机C ++ DLL方法。例如:

Inside a C# Console application, I'm importing a native C++ DLL methods. for example:

    [DllImport("MyDll.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.Cdecl)]
    public static extern int MyMethod(IntPtr somePointer);

执行时,正在打印 MyMethod()

假设我无法更改DLL,仍然如何抑制它的输出?

Assuming I can't change the DLL, how can I still suppress it's output?

推荐答案

http://social.msdn.microsoft.com/Forums/vstudio / en-US / 31a93b8b-3289-4a7e-9acc-71554ab8fca4 / net-gui-application-native-library-console-stdout-redirection-via-anonymous-pipes

我删除了他们尝试重定向它的部分,因为如果您进一步阅读,它说在多次调用时他们遇到了问题。

I removed the part where they try to redirect it because if you read further, it says they were having issues when it was called more than once.

 public static class ConsoleOutRedirector
    {
    #region Constants

    private const Int32 STD_OUTPUT_HANDLE = -11;

    #endregion

    #region Externals

    [DllImport("Kernel32.dll")]
    extern static Boolean SetStdHandle(Int32 nStdHandle, SafeHandleZeroOrMinusOneIsInvalid handle);
    [DllImport("Kernel32.dll")]
    extern static SafeFileHandle GetStdHandle(Int32 nStdHandle);

    #endregion

    #region Methods

    public static void GetOutput(Action action)
    {
      Debug.Assert(action != null);

      using (var server = new AnonymousPipeServerStream(PipeDirection.Out))
      {
        var defaultHandle = GetStdHandle(STD_OUTPUT_HANDLE);

        Debug.Assert(!defaultHandle.IsInvalid);
        Debug.Assert(SetStdHandle(STD_OUTPUT_HANDLE, server.SafePipeHandle));
        try
        {
          action();
        }
        finally
        {
          Debug.Assert(SetStdHandle(STD_OUTPUT_HANDLE, defaultHandle));
        }
      }
    }

    #endregion
  }

和使用示例:

[DllImport("SampleLibrary.dll")]
extern static void LetterList();

private void button1_Click(object sender, EventArgs e)
{
  ConsoleOutRedirector.GetOutput(() => LetterList());
}

这篇关于抑制控制台从导入的DLL打印的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆