c# - 通过 C++ dll 或 C++ exe 编写 C# GUI

标签 c# c++ dll

我有一个 C++ 控制台 Exe,它可以进行一些编程。现在我想编写一个 C# GUI,它执行一些 C++ exe 执行的编程。我正在考虑几种方法,

  1. 用 C++ 从头开始​​编写所有编程的 C# GUI。(我不想这样做,因为它需要大量的返工)
  2. 构建一个 C++ dll 来进行编程并将其导入 GUI 应用程序。(现在我有一个问题。我如何在 c++ dll 中捕获例程的输出并将其显示在 GUI 中?我应该返回输出吗作为应用程序调用的每个例程的字符串。?因为我不知道托管 C++,我将构建一个非托管 C++ dll。)

最佳答案

构建一个 C++/CLI dll 真的没有那么难。您基本上使用非托管 C++ 代码,除了您定义一个“public ref class”,它托管您希望 C# 代码看到的函数。

你要返回什么样的数据?单个数字、数字矩阵、复杂对象?

更新:由于已经明确“输出”是 iostreams,here is a project演示将 cout 重定向到调用该库的 .NET 应用程序。重定向 clogcerr 只需要在现有重定向之后在 DllMain 中添加一些额外的行。

The zip file包括 VS2010 项目文件,但源代码应该也可以在 2005 或 2008 中运行。

iostreams 捕获功能包含在以下代码中:

// compile this part without /clr
class capturebuf : public std::stringbuf
{
protected:
    virtual int sync()
    {
        // ensure NUL termination
        overflow(0);
        // send to .NET trace listeners
        loghelper(pbase());
        // clear buffer
        str(std::string());
        return __super::sync();
    }
};

BOOL WINAPI DllMain(_In_ HANDLE _HDllHandle, _In_ DWORD _Reason, _In_opt_ LPVOID _Reserved)
{
    static std::streambuf* origbuf;
    static capturebuf* altbuf;
    switch (_Reason)
    {
    case DLL_PROCESS_ATTACH:
        origbuf = std::cout.rdbuf();
        std::cout.rdbuf(altbuf = new capturebuf());
        break;
    case DLL_PROCESS_DETACH:
        std::cout.rdbuf(origbuf);
        delete altbuf;
        break;
    }

    return TRUE;
}

// compile this helper function with /clr
void loghelper(char* msg) { Trace::Write(gcnew System::String(msg)); }

关于c# - 通过 C++ dll 或 C++ exe 编写 C# GUI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4687901/

相关文章:

c# - 如何将 Expires Header 添加到 iis7 中的自定义文件?

c++ - 类模板化 std::set 键类型

C++字符串大小减去整数不是期望值,为什么?

.net - 是否可以在.NET DLL中添加/删除/更改嵌入式资源?

c#从列表中的字段中获取列表

c# - 我可以在重载的结构运算符中使用常量参数吗?

c++ - 使用 LARGE_INTEGER 返回错误 error C2679 : '=' binary no operator found which takes a right-hand operand

c++ - Irrlicht 编译,但在执行时崩溃

dll - VB 6.0 DLL 中的错误处理

c# - 简单发布到 Web Api