Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unable to call a thread in dll file

I am trying to create a dll which will create a thread when you load him for some reason the thread function is not doing anything.. :\

this is my code:

dllthread != null.. why its not working?

#include "stdafx.h"
DWORD WINAPI ThreadProc(
  __in  LPVOID lpParameter
)
{

    std::ofstream myfile;
    myfile.open ("example.txt");
    myfile << "Writing this to a file.\n";
    myfile.close();

    return 0;
}

BOOL APIENTRY DllMain( HMODULE hModule,
                       DWORD  ul_reason_for_call,
                       LPVOID lpReserved
                     )
{

    switch (ul_reason_for_call)
    {
    case DLL_PROCESS_ATTACH:    
        DWORD DllThreadID;
        HANDLE DllThread; //thread's handle

        DllThread=CreateThread(NULL,0,&ThreadProc,0,0,&DllThreadID);
// 
        if (DllThread == NULL)
            MessageBox(NULL, L"Error", L"Error", MB_OK);

        CloseHandle(DllThread);
        break;
    case DLL_THREAD_ATTACH:
    case DLL_THREAD_DETACH:
    case DLL_PROCESS_DETACH:


        break;
    }
    return TRUE;
}
like image 547
D_R Avatar asked Nov 25 '11 20:11

D_R


1 Answers

Instead of starting the thread from DllMain() export a function that would launch the thread instead:

extern "C" __declspec(dllexport) void start_thread()
{
    DWORD DllThreadID;
    HANDLE DllThread; //thread's handle

    DllThread=CreateThread(NULL,0,ThreadProc,0,0,&DllThreadID);
    if (DllThread == NULL)
        MessageBox(NULL, L"Error", L"Error", MB_OK);
    else
        CloseHandle(DllThread);

}

After calling LoadLibrary() use GetProcAddress() to get access to the start_thread() function.

Hope this helps.

like image 177
hmjd Avatar answered Sep 30 '22 16:09

hmjd