分享

如何在DLL里使用cout或者printf(整)

 imelee 2017-09-28
    一般的对话框,文档,包括驱动程序里可以使用TRACE。但DLL里只能用OutputString,不能使用printf一类的可以格式化输出的函数吗?下面的单引号实际上是双引号,BLOG系统显示的时候自动替换的。

You can do that. All you need to do is to REDIRECT the input/output to
stdout/stdin.

You can use WIN32 API
BOOL WINAPI AllocConsole(void)
to allocate a console for the calling process (/DLL).

Further you can wrap in a class


CConsole:: CConsole()
{
AllocConsole();
freopen("CONOUT$","w+t",stdout);
freopen("CONIN$","r+t",stdin);
}

CConsole:: ~CConsole()
{
fclose(stdout);
fclose(stdin);
FreeConsole();
}


Then when you initialize your DLL, you create an instance of CConsole, and
in the constructor, the console will be attached to the process. Then you
can use cout, cin to redirect input/output stream.

Good luck.

针对WIN32 DLL加入下面的代码就可以了。
BOOL APIENTRY DllMain( HANDLE hModule,
                      DWORD  ul_reason_for_call,
                      LPVOID lpReserved
                      )
{
    switch (ul_reason_for_call)
    {
    case DLL_THREAD_ATTACH:
    case DLL_PROCESS_ATTACH:
        {
            AllocConsole();
            freopen("CONOUT$","w+t",stdout);
            freopen("CONIN$","r+t",stdin);
        }
        printf("Console has been built:"__TIME__"\n");
        break;
    case DLL_THREAD_DETACH:
    case DLL_PROCESS_DETACH:
        {
            fclose(stdout);
            fclose(stdin);
            FreeConsole();
        }
        break;
    }
    return TRUE;
}

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多