WPF 重定向DLL stdout

场景

在wpf程序中调用dll,dll中包含了stdout stdin之类的输出输入流,程序启动后,并不会写入到console的流中,这个时候需要用底层的API进行重定向
docs: https://docs.microsoft.com/en-us/dotnet/api/system.console.setout?view=netcore-3.1

QA:https://stackoverflow.com/questions/8555002/how-can-i-stream-data-from-a-managed-assembly-to-a-native-library-and-back-again

https://www.codeguru.com/csharp/csharp/cs_misc/sampleprograms/article.php/c7259/InterProcess-Communication-in-NET-Using-Named-Pipes-Part-1.htm

code

winapi定义

     [DllImport("kernel32.dll", EntryPoint = "GetStdHandle", SetLastError = true, CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
        private static extern IntPtr GetStdHandle(int nStdHandle);

        [DllImport("Kernel32.dll", SetLastError = true)]
        public static extern int SetStdHandle(int device, IntPtr handle);

        [DllImport("kernel32.dll", SetLastError = true)]
        static extern bool AttachConsole(uint dwProcessId);

        [DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true)]
        static extern bool FreeConsole();

        [DllImport("kernel32.dll", SetLastError = true)]
        private static extern bool GenerateConsoleCtrlEvent(CtrlTypes dwCtrlEvent, uint dwProcessGroupId);

        [DllImport("kernel32.dll")]
        static extern bool SetConsoleCtrlHandler(ConsoleCtrlDelegate handlerRoutine, bool add);

        delegate bool ConsoleCtrlDelegate(CtrlTypes ctrlType);

调用

            FileStream fs = new FileStream("Test.txt", FileMode.Create);
            Encoding encoding = System.Text.Encoding.GetEncoding("UTF-8");

            StreamWriter standardOutput = new StreamWriter(fs, encoding);
            //set handle
            SetStdHandle(-11,fs);
            SetStdHandle(-12,fs);

重定向到到其他流

目前好像仅支持file 流,找了一些资料好像其他流实现需要通过windows pipe来实现,简直太麻烦了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值