[C#从C ++ DLL捕获输出

问题描述 投票:0回答:1

我有一个C#Windows应用程序,该应用程序调用DLL中的C ++函数。这些DLL函数通过printf()std::cout写入控制台。

当我运行C#应用程序时,我希望能够看到此输出,但是找不到实现此目的的方法。

我该怎么做?

c# c++ dll
1个回答
0
投票

我认为您有一个.NET Forms应用程序。如果是这样,您可以简单地为自己分配一个用于stdout的控制台窗口。

这是一个最小的示例:

// stdout.dll
extern "C" {
  __declspec(dllexport) void __cdecl HelloWorld()
  {
    cout << "Hello World" << endl;
  }
}

将标准处理程序初始化为零,并在程序启动时分配一个新的控制台窗口。

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

在程序流程中调用extern函数:

private void btnHelloWorld_Click(object sender, EventArgs e)
{
    Program.HelloWorld();
}

Hello World Console Window

© www.soinside.com 2019 - 2024. All rights reserved.