i have a bunch of Console.WriteLines in my code that I can observe at runtime. I communicate with a native library that I also wrote.
I'd like to stick some printf's in the native library and observe them too. I don't see them at runtime however.
I've created a convoluted hello world app to demonstrate my problem. When the app runs, I can debug into the native library and see that the hello world is called. The output never lands in the textwriter though. Note that if the same code is run as a console app then everything works fine.
C#:
[DllImport("native.dll")]
static extern void Test();
StreamWriter writer;
public Form1()
{
InitializeComponent();
writer = new StreamWriter(@"c:\output.txt");
writer.AutoFlush = true;
System.Console.SetOut(writer);
}
private void button1_Click(object sender, EventArgs e)
{
Test();
}
and the native part:
__declspec(dllexport) void Test()
{
printf("Hello World");
}
Update:
hamishmcn below started talking about debug/release builds. I removed the native call in the above button1_click
method and just replaced it with a standard Console.WriteLine
.net call. When I compiled and ran this in debug mode the messages were redirected to the output file. When I switched to release mode however the calls weren't redirected. Console redirection only seems to work in debug mode. How do I get around this?
You will need to switch your Solution Configuration from "Debug" to "Release". You can do this at the top of Visual Studio, or within the Project Properties under the Build tab. When you next build your project, the output files will be placed in the Release folder.
The Console. ReadLine() method in C# is used to read the next line of characters from the standard input stream.
WriteLine(String, Object, Object) Writes the text representation of the specified objects, followed by the current line terminator, to the standard output stream using the specified format information.
Console. writeline() goes to a console window: the black command / dos prompt.
Perhaps your native library, for some reason, doesn't know about the console.
You could try calling GetConsole an see if a handle is returned. If not you could try allocating your own console to see if that works.
Good luck! :-)
Update:
I wrote a sample app too (console C# app calling native C++ dll) and both the C# Console.WriteLine and the native printf appear on the console... So what are we missing?
Do you always run it in debug mode - do you see a console window at all if you run it in release mode?
Update 2:
Sorry, I should say I see the text on the console, but if I set the Console output to a StreamWriter, like you have in your example, then only the WriteConsole text goes to the output file, the printf
s still go to the screen
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With