Paul
Paul

Reputation: 6881

Getting a pointer variable in a process by name using WinAPI

I'm not sure how clear the title of the question is. Here's what I'm trying to do:

I have a process, which uses DLL libraries as plugins. Those libraries use functions, synchronized with a critical section object . I want all DLL functions to be synchronized with the same critical section object. I thought about the following: the first DLL will initialize a critical section object, and other DLLs will use it too, instead of initializing a new one. But how can I get the pointer to the critical section object of the first DLL?

One solution I thought of is using a Named Shared Memory, and placing the pointer to the critical section object there. It will work, but it feels like shooting a fly with a bazooka. Is there a simpler and more idiomatic way to create a named object with a retrievable pointer?

Upvotes: 1

Views: 145

Answers (2)

Remy Lebeau
Remy Lebeau

Reputation: 596206

Use a named Mutex. You do not have to pass it around across DLL boundaries. Each DLL can individually call CreateMutex(), specifying the same name, and they will each get their own local HANDLE to the same mutex object in the kernel, thus allowing syncing with each other. Just make sure each DLL calls CloseHandle() when it is done using the mutex. The best place to do both is in each DLL's entry point function, eg:

HANDLE hMutex = NULL;

BOOL WINAPI DllEntryPoint(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpReserved)
{
    switch( fdwReason ) 
    { 
        case DLL_PROCESS_ATTACH:
            hMutex = CreateMutex(NULL, FALSE, TEXT("MySharedMutex"));
            if (hMutex == NULL) return FALSE;
            break;

        case DLL_PROCESS_DETACH:
            if (hMutex != NULL)
            {
                CloseHandle(hMutex);
                hMutex = NULL;
            } 
            break;
    }

    return TRUE;
}

Upvotes: 2

vlad_tepesch
vlad_tepesch

Reputation: 6883

One Dll should be responsible for the Management of the critical section object. This dll may also export functions to work with it. This dll should create the object during its load and provide (exports) a function that returns the objects pointer.

Upvotes: 3

Related Questions