我有一个C#Windows应用程序,该应用程序调用DLL中的C ++函数。这些DLL函数通过printf()
和std::cout
写入控制台。
当我运行C#应用程序时,我希望能够看到此输出,但是找不到实现此目的的方法。
我该怎么做?
我认为您有一个.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();
}