cout and printf Works On Dll Built In Debug Not Release

落爺英雄遲暮 提交于 2021-01-27 05:56:33

问题


I've built a DLL that gets injected into a console application usually via SetWindowHookEx. Its important for the DLL to output information to the console which I have been doing with std::cout. The DLL was nearing completion until I tried building the DLL in release mode which rendered all cout lines useless. I've verified the the DLL is injecting and is executing by doing a simple null dereference that causes the program to crash in the dllmain function. Same story with std::printf.

void onAttach()
{
    //WARNING THIS IS A DEMONSTRATION
    std::cout<<"test"<<std::endl;
    //int* intPtr = 0;
    //*intPtr = 3; //This causes a crash
}

// entry point
BOOL WINAPI DllMain ( HMODULE hModule, DWORD dwReason, LPVOID lpReserved )
{
    switch ( dwReason )
    {
        case DLL_PROCESS_ATTACH:
            DisableThreadLibraryCalls ( hModule );
            CreateThread ( NULL, 0, ( LPTHREAD_START_ROUTINE ) onAttach, NULL, 0, NULL );
            return true;
        break;

        case DLL_PROCESS_DETACH:
            return true;
        break;
    }
}

I really don't know how to approach this problem. Is the Release linker somehow excluding dependencies?

I'm using MSVS 2010 and default release/debug configuration setup. The debug dll is about 5,137kb and the release dll is only 23kb.


回答1:


You should not do anything in DllMain which depends on another DLL. You violate that at least three times: printf and std::cout depend on the CRT (which in turn depends on Win32 DLLs) and CreateThread depends on Kernel32.DLL.

DllMain is intended for simple things like zeroing variables etc.




回答2:


I know @salters is correct in stating that no calls to other libraries should be made in a DLL, but after trial and error I've found that compiling the DLL's in x64 configuration (instead of x86) the DLL's can "cout" or show use the "MessageBox" function without any issues (can likely call functions from a number of other libraries). Hope this helps :).



来源:https://stackoverflow.com/questions/14208569/cout-and-printf-works-on-dll-built-in-debug-not-release

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!