2

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?

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Gunner
  • 125
  • 10
  • https://stackoverflow.com/questions/13493149/calling-opencv-c-code-in-c-sharp-application – Mujahid Daud Khan Oct 17 '19 at 08:18
  • 1
    Move the DLL to a separate process. Have the C# app spawn it when needed, and read from its `stdout` output. See the [`Process`](https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.process) class and its [`StartInfo.RedirectStandardOutput`](https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.processstartinfo.redirectstandardoutput#System_Diagnostics_ProcessStartInfo_RedirectStandardOutput) and [`StandardOutput`](https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.process.standardoutput#System_Diagnostics_Process_StandardOutput) properties. – Remy Lebeau Oct 17 '19 at 08:35

1 Answers1

2

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();
}

Hello World Console Window

urbanSoft
  • 686
  • 6
  • 14
  • Not usually what they mean when they use the word "capture". Doing it this way doesn't require any code, simply Project > Properties > Application tab, "Output type" = Console. – Hans Passant Oct 31 '19 at 15:02
  • The headline says "capture" but the content: "I would like to [...] _see_ this output". You're right "Output type" => Console works as well. I favour doing it programatically though but this depends on the actual use case. – urbanSoft Oct 31 '19 at 15:12