抑制控制台从导入的DLL打印

编程入门 行业动态 更新时间:2024-10-22 17:18:18
本文介绍了抑制控制台从导入的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?

推荐答案

从 social.msdn.microsoft/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打印

本文发布于:2023-10-27 15:56:14,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1533844.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:控制台   抑制   DLL

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!