I have a C# Windows application that makes calls to C++ functions in a DLL.
These DLL functions write to the console via printf() and std::cout.
When I run my C# application, I would like to be able to see this output, but I cannot find a way of achieving this.
How can I do this?
I reckon you have a .NET Forms Application. If so you could simply allocate yourself a console window which is used for stdout.
Here's a minimal example:
// stdout.dll
extern "C" {
  __declspec(dllexport) void __cdecl HelloWorld()
  {
    cout << "Hello World" << endl;
  }
}
Initialize the standard handels to zero and allocate a new console window at program startup.
static class Program
{
    [DllImport("kernel32.dll")]
    public static extern bool SetStdHandle(int stdHandle, IntPtr handle);
    [DllImport("kernel32.dll")]
    public static extern bool AllocConsole();
    [DllImport("stdout.dll")]
    extern public static void HelloWorld();
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        SetStdHandle(-10, IntPtr.Zero); // stdin
        SetStdHandle(-11, IntPtr.Zero); // stdou
        SetStdHandle(-12, IntPtr.Zero); // stderr
        AllocConsole();
        /* ... */
    }
 }
Within the program flow call the extern function:
private void btnHelloWorld_Click(object sender, EventArgs e)
{
    Program.HelloWorld();
}

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