开发者

Using std::cout in DLL called from C# [duplicate]

开发者 https://www.devze.com 2023-03-02 14:38 出处:网络
This question already has answers here: 开发者_C百科 Redirecting cout to a console in windows (11 answers)
This question already has answers here: 开发者_C百科 Redirecting cout to a console in windows (11 answers) Closed 3 years ago.

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.


cout is wired up by the C/C++ runtime when main() executes. So if the C++ code is limited to the DLL, there probably is no cout to write to. (This is an oversimplification but you get the idea.)

Console.Out is a System.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?


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 link std::cout.

0

精彩评论

暂无评论...
验证码 换一张
取 消