问题描述
网络上到处都是类似的问题,因此在回答标准/简单答案之前,请仔细阅读. :-)
The web is littered with similar questions, so please read carefully before answering with the standard/simple answer. :-)
使这个问题与众不同的是:
What sets this question apart is:
- 控制台输出来自不受管理的 DLL ,而不是外部应用程序或进程. 该代码正在进程内"运行.
- DLL正在使用"printf".或同等的东西,根据我所做的研究,似乎与"stdout"不同.
- The console output is coming from an unmanaged DLL, NOT an external application or process. The code is running "in-process".
- The DLL is using "printf" or an equivalent, which, from the research I've done, seems to be different from "stdout".
现在对问题进行简单描述.我有一个要在C#中使用的外部DLL.该DLL是用Fortran编写的,尽管我认为这不是很明显. DLL将信息写入控制台.我想捕捉 控制台输出并使其对用户可见.
Now for a simple description of the problem. I have an external DLL that I want to use in C#. The DLL is written in Fortran, though I don't think that's salient. The DLL writes information to the console. I want to capture the console output and make it visible to the user.
我尝试了很多不同的组合和排列,但均未成功.最常见和最明显的解决方案是,您将在众多类似的线程中找到一种解决方案,它取决于"Console.SetOut"中的一种或另一种形式. 除非我做的事情完全错误,否则在我描述的情况下这是行不通的. (在启动单独的应用程序时效果很好,但不适用于进程内的东西.)
I have tried a LOT of different combinations and permutations with no success. The most common and obvious solution, and the one you'll find in numerous similar threads, depends in one form or another on "Console.SetOut". Unless I'm doing something completely wrong, this does not work in the scenario I've described. (It works great when launching a separate application, but not for something in-process.)
任何帮助将不胜感激!
谢谢!
布拉德.
推荐答案
[System.Runtime.InteropServices.DllImport("Kernel32.dll", SetLastError = true)]
public static extern int SetStdHandle(int device, IntPtr handle);
const int STD_OUTPUT_HANDLE = -11;
[DllImport("MyExternal.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern void HelloWorld();
private void CaptureOutput()
{
using (var fileStream = new FileStream("Test.txt", FileMode.Create))
{
SetStdHandle(STD_OUTPUT_HANDLE, fileStream.SafeFileHandle.DangerousGetHandle());
HelloWorld();
Console.OpenStandardOutput().Flush();
fileStream.Flush();
}
}
我仍然需要做更多的测试,但是我最初的测试很吸引人.显然,上面的代码需要更多的错误检查等,但它似乎完全可以满足我的要求.
I still need to do more testing, but my initial tests worked like a charm. Obviously the above code needs more error checking, etc., but it seems to be doing exactly what I wanted.
如果可以,我将:
- 感谢此帖子.
- 回来,将其标记为答案.
布拉德.
这篇关于从DLL重定向控制台输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!