场景
在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来实现,简直太麻烦了