【发布时间】:2011-04-25 17:27:36
【问题描述】:
我正在尝试在动态加载的 dll 中使用静态类变量和函数,它们是原始类的子类。这些静态成员用于静态链接的类;这个类使用工厂加载 dll,这些 dll 应该可以访问静态函数和变量。这是一个简短的示例作为简单的演示(即,不要指望它能够编译;实际的类每个都有超过 1000 行):
//GenericBase.h-------------------------
#include "GenericDll.h"
class GenericBase{
public:
GenericBase()
{
mClassA.addInstance(this);
}
static int mNumInstances;
static void DoSomething();
static void Foo();
static void LoadDlls();
set<GenericDll*> mPlugins;
};
//--------------------------------------
//GenericDll.h--------------------------
class GenericDll : public GenericBase
{
void Function();
};
extern "C" __declspec (dllexport) GenericDll* CreateModule()
{
GenericDll * module = new GenericDll();
return module;
}
//--------------------------------------
//GenericBase.cpp-----------------------
void GenericBase::DoSomething()
{
for (it = mPlugins.begin(); it != mPlugins.end(); it++)
it->Function();
}
//--------------------------------------
//GenericDll.cpp------------------------
void GenericDll::Function()
{
mNumInstances++; // mNumInstancesin GenericDll and mNumInstances in
// the static linked GenericBase have different
// addresses
cout << &mNumInstances<<endl;
Foo(); // again, the address Foo() is different in the dll
}
//--------------------------------------
//main.cpp
int main(){
GenericBase g;
GenericBase::LoadDlls(); //not shown
GenericBase::DoSomething();
cout << &mNumInstances << endl;
}
//Output: these are the addresses of the mNumInstances
>> 00FAC3B0
>> 0F753398
>> 004D3398
所以,总体的问题或目标是:我怎样才能使静态链接对象的 mNumInstances 的地址与该对象子类的动态加载的 dll 类相同?
希望这足够清楚,并且有意义!
【问题讨论】:
-
基本上,你不能。 DLL 并非旨在成为共享数据的一种方式。
-
为什么不在你的基础中为你的静态数据提供访问器方法并使数据成员正确地私有?最坏的情况,只需向它添加一个“int * getNumInstancesPtr()”......尽管它的非封装做法很糟糕。根据您的子类想要对数据执行的操作,更合适的一组函数将是 incrementInstanceCount()/decrementInstanceCount() 之类的......
标签: c++ variables dll static subclass