在从 C# 调用的 DLL 中使用 std::cout
我的 Windows 应用程序有 C# 部分和 C++ 部分。 C# 应用程序在运行时会显示一个控制台窗口。
C++ 代码被编译成 DLL,可通过 P/Invoke 从 C# 使用。
问题是通过 std::cout 从 C++ DLL 打印文本不会打印任何内容。从 C# 打印效果很好。
我怀疑 C# 已经接管了控制台,因此 C++ 无法获取它的句柄。解决方法可能是从 C# 获取控制台句柄,将其传递给 C++,然后使用它将 std::cout 连接到控制台窗口。但我不知道该怎么做。
有什么想法吗?
编辑:我的 C++ 代码是非托管的。
My Windows app has a C# part and a C++ part. The C# app shows a console window when it's ran.
The C++ code is compiled into a DLL which is used from C# via P/Invoke.
The problem is that printing text from the C++ DLL via std::cout doesn't print anything. Printing from C# works fine.
I suspect C# has taken over the console, so C++ can't get a handle to it. The fix might be to get a console handle from C#, pass it over to C++, and use it to connect std::cout to the console window. But I don't know how to go about doing that.
Any ideas?
Edit: My C++ code is unmanaged.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当
main()
执行时,cout
由 C/C++ 运行时连接。因此,如果 C++ 代码仅限于 DLL,则可能没有可写入的cout
。 (这过于简单化了,但您明白了。)Console.Out 是一个 System.IO.TextWriter。如果您的 C++ 代码是托管的,您可以将其传递给 DLL 并对其进行写入。但如果您通过 P/Invoke 调用它,我怀疑情况并非如此。也许使用命名管道?
cout
is wired up by the C/C++ runtime whenmain()
executes. So if the C++ code is limited to the DLL, there probably is nocout
to write to. (This is an oversimplification but you get the idea.)Console.Out
is aSystem.IO.TextWriter
. If your C++ code is managed, you can pass that to your DLL and write to it. But if you're calling it via P/Invoke I suspect that's not the case. Maybe use a named pipe?基本上,C++ 运行时没有正确链接到控制台,因为它应该创建它。有一个
std::sync_with_stdio
函数应该正确链接std::cout
。Basically, the C++ runtime isn't linked to the console correctly, because it's supposed to create it. There is a
std::sync_with_stdio
function that should correctly linkstd::cout
.