从 C++ DLL 向控制台打印消息
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2354138/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Printing messages to console from C++ DLL
提问by Rakesh K
I have an application which uses C# for front end and C++ DLL for the logic part. I would want to print error messages on console screen from my C++ DLL even when the C# GUI is present. Please let me know how to do this.
我有一个应用程序,它使用 C# 作为前端,使用 C++ DLL 作为逻辑部分。即使存在 C# GUI,我也希望从我的 C++ DLL 在控制台屏幕上打印错误消息。请让我知道如何做到这一点。
Thanks, Rakesh.
谢谢,拉克什。
回答by Francis
回答by Greg Najda
You can use AllocConsole()to create a console window and then write to standard output.
您可以使用AllocConsole()创建一个控制台窗口,然后写入标准输出。
If you are using C or C++ standard I/O functions (as opposed to direct win32 calls), there are some extra steps you need to take to associate the new console with the C/C++ standard library's idea of standard output. http://www.halcyon.com/~ast/dload/guicon.htmexplains what you have to do and why, with complete code.
如果您使用 C 或 C++ 标准 I/O 函数(而不是直接的 win32 调用),则需要采取一些额外的步骤来将新控制台与 C/C++ 标准库的标准输出概念相关联。http://www.halcyon.com/~ast/dload/guicon.htm用完整的代码解释了你必须做什么以及为什么。
回答by Ignacio Vazquez-Abrams
Unless the application is started from a console, stdin, stdout, and stderr won't even exist and any attempt to use e.g. printf()
will fail. Either open your own console or use a debugging mechanism such as OutputDebugString()
suggested earlier.
除非应用程序是从控制台启动的,否则 stdin、stdout 和 stderr 甚至都不存在,任何使用 eg 的尝试printf()
都将失败。要么打开您自己的控制台,要么使用OutputDebugString()
前面建议的调试机制。
回答by matrixanomaly
If dealing with DLLs and Service EXEs like COM/DCOM or any other ATL project, you can also use this line of code to print out diagnostic messages in the form of MessageBox
windows as an alternative to printing messages to the console:
如果处理 DLL 和服务 EXE,如 COM/DCOM 或任何其他 ATL 项目,您还可以使用这行代码以MessageBox
窗口的形式打印诊断消息,作为将消息打印到控制台的替代方法:
MessageBox(NULL, L"Com Object Function Called", L"COMServer", MB_OK | MB_SETFOREGROUND);
MessageBox(NULL, L"Com Object Function Called", L"COMServer", MB_OK | MB_SETFOREGROUND);
Example cases where I have used this include the _tWinmain
function, as well as constructors and destructors to keep track of instances.
我使用它的示例案例包括_tWinmain
函数,以及用于跟踪实例的构造函数和析构函数。