Can vc++;使用运行时dll加载时在库中共享静态 我正在使用微软C++研究一个插件类型系统。我的问题是我无法在主程序和插件库之间共享共享库中的静态变量

Can vc++;使用运行时dll加载时在库中共享静态 我正在使用微软C++研究一个插件类型系统。我的问题是我无法在主程序和插件库之间共享共享库中的静态变量,c++,windows,visual-c++,dll,dllexport,C++,Windows,Visual C++,Dll,Dllexport,主程序: #include "stdafx.h" #include "windows.h" #include "..\EngineLib\Engine.h" typedef void(*PluginFuncPtrType)(void); int main() { printf("Main Test.\n"); HINSTANCE hRuntimeDll = LoadLibrary(L"PluginLib.dll"); if (!hRuntimeDll) {

主程序:

#include "stdafx.h"
#include "windows.h"
#include "..\EngineLib\Engine.h"

typedef void(*PluginFuncPtrType)(void);

int main()
{
    printf("Main Test.\n");

    HINSTANCE hRuntimeDll = LoadLibrary(L"PluginLib.dll");
    if (!hRuntimeDll) {
        printf("Could not load the dynamic library.\n");
    }

    PluginFuncPtrType pluginFuncPtr = (PluginFuncPtrType)GetProcAddress(hRuntimeDll, "PluginFunc");
    if (!pluginFuncPtr) {
        printf("Could not load the function from dynamic library.\n");
    }
    else {
        pluginFuncPtr();
        printf("Main engine counter %i.\n", EngineFunc());
        pluginFuncPtr();
        printf("Main engine counter %i.\n", EngineFunc());
        pluginFuncPtr();
        printf("Main engine counter %i.\n", EngineFunc());
    }

    printf("Press any key to exit...");
    getchar();
}
主程序(静态链接)和插件dll(也在此共享库中静态链接)使用的共享库

共享库标题(Engine.h):

main.exe的输出:

Main Test.
PluginFunc engine counter=1
Main engine counter 1.
PluginFunc engine counter=2
Main engine counter 2.
PluginFunc engine counter=3
Main engine counter 3.
Press any key to exit...
Main.exe静态链接到EngineLib.libPluginLib.dll静态链接到EngineLib.lib

Main不链接PluginLib.dll,而是在运行时加载它

据我所知,当使用LoadLibrary在运行时加载dll时,它会获得自己的虚拟内存地址空间,因此会将不同的静态变量静态链接到主程序中的同一个库中。我相信在Linux上,动态加载的库确实共享相同的虚拟内存空间

我的问题是,Windows是否可以使用任何方法来允许动态加载的dll使用与静态链接库相同的静态变量?

创建dll。“EngineStatics.dll”。在此dll中定义静态,并使用_declspec(dllexport)导出它

在exe中,添加对上述dll的依赖项。并用uu declspec(dllimport)声明相同的静态

在插件dll中,在同一dll上添加依赖项,并使用DelcSec(dllimport)导入该依赖项



这似乎比我最初的答案要简单得多:直接从.exe导出static,使用工具生成导出库,然后根据exe的库文件创建插件dll链接。

我不想直接访问static _engineCounter变量。在我的简化示例中,静态变量表示加载了EngineLib update副本的内容,并且该库的两个不同用户需要查看彼此的更新。
#include "stdafx.h"
#include "Engine.h"
#include <stdio.h>

static int _engineCounter = 1;

int EngineFunc()
{
    return _engineCounter++;
}
#pragma once

#include "stdafx.h"
#include <stdio.h>
#include "..\EngineLib\Engine.h"

extern "C" __declspec(dllexport) void PluginFunc(void);
#include "Plugin.h"

void PluginFunc(void)
{
    printf("PluginFunc engine counter=%i\n", EngineFunc());
}
Main Test.
PluginFunc engine counter=1
Main engine counter 1.
PluginFunc engine counter=2
Main engine counter 2.
PluginFunc engine counter=3
Main engine counter 3.
Press any key to exit...