简体   繁体   中英

C# capture output from C++ DLL

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

Hello World 控制台窗口

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM