简体   繁体   English

使用WinAPI按名称获取进程中的指针变量

[英]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. 我有一个使用DLL库作为插件的过程。 Those libraries use functions, synchronized with a critical section object . 这些库使用与关键节对象同步的函数。 I want all DLL functions to be synchronized with the same critical section object . 我希望所有DLL函数都与同一个关键部分对象同步。 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. 我考虑了以下问题:第一个DLL将初始化关键部分对象,其他DLL也将使用它,而不是初始化一个新的对象。 But how can I get the pointer to the critical section object of the first DLL? 但是,如何获得指向第一个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? 有没有更简单,更惯用的方法来创建带有可检索指针的命名对象?

One Dll should be responsible for the Management of the critical section object. 一个Dll应该负责关键部分对象的管理。 This dll may also export functions to work with it. 此dll可能还导出了要使用的函数。 This dll should create the object during its load and provide (exports) a function that returns the objects pointer. 该dll在加载期间应创建对象,并提供(导出)返回对象指针的函数。

Use a named Mutex. 使用命名的互斥锁。 You do not have to pass it around across DLL boundaries. 您不必跨DLL边界传递它。 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. 每个DLL可以单独调用CreateMutex() ,并指定相同的名称,并且每个DLL都会将自己的本地HANDLE获取到内核中的同一互斥对象,从而允许彼此同步。 Just make sure each DLL calls CloseHandle() when it is done using the mutex. 只要确保每个DLL使用互斥锁完成后都调用CloseHandle() The best place to do both is in each DLL's entry point function, eg: 两者的最佳选择是在每个DLL的入口点函数中,例如:

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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM