Microsoft C++を使用しているプラグインタイプのシステムを調べています。私が持っている問題は、メインプログラムとプラグインライブラリの間で共有ライブラリの静的変数を共有できないということです。ランタイムdllローディングを使用する場合、vC++でスタティックライブラリを共有できます
メインプログラム:
#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):
#pragma once
#include <stdio.h>
int EngineFunc();
共有ライブラリの実装:
#include "stdafx.h"
#include "Engine.h"
#include <stdio.h>
static int _engineCounter = 1;
int EngineFunc()
{
return _engineCounter++;
}
プラグインDLLヘッダ(Plugin.h):
#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.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.libに対して PluginLib.dllは静的リンクEngineLib.libに対してです。
メインはPluginLib.dllとリンクせず、実行時にロードします。
DLLが実行時にLoadLibraryを使用してロードされるとき、それはそれ自身の仮想メモリアドレス空間を取得し、したがって同じ静的変数を静的にメインプログラムにリンクすることになります。私はLinuxの動的にロードされたライブラリは、同じ仮想メモリ空間を共有すると信じています。
私の質問は、動的にロードされたDLLが静的にリンクされたライブラリと同じ静的変数を使用できるようにWindowsで使用できるアプローチがあるかどうかです。
static _engineCounter変数に直接アクセスしたくありません。私の根本的に単純化した例では、静的変数は、EngineLibの更新をロードしたものと、そのライブラリの2人の異なるユーザがお互いのアップデートを見る必要があるものを表しています。 – sipwiz