5

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.

2

2 Answers 2

2

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?

1
  • It's wired up when the C++ runtime library initializes, which does happen for DLLs as well.
    – Ben Voigt
    Jul 2, 2011 at 23:38
0

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.

1
  • Thanks, but sync_with_stdio (the static function in ios_base) didn't help.
    – coder123
    Jul 2, 2011 at 20:38

Not the answer you're looking for? Browse other questions tagged or ask your own question.