access static variables/functions in a statically linked library from a dynamic dll
I am trying to use static class variables and functions in a dynamically loaded dll, which are subclasses of the original class. These static members are used in a statically linked class; this class loads the dlls using a factory,开发者_如何学Python and these dlls should have access to the static functions and variables. Here is a short example as a simple demonstration (i.e., don't expect it to compile; the actual classes have over 1000 lines each):
//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
So, the overall question or goal is: how can I make the address of mNumInstances the same for the statically linked object, and the dynamically loaded dll classes that subclass this object?
Hopefully this is clear enough, and makes sense!
To achieve what you wanted to do, you would need to make the shared (copied per DLL) static library a DLL itself.
Think of a DLL as more like an EXE.
Also, be very careful with library versions and compiler and linker settings when returning things like set<> (what ever it is) as things like alignment, data type sizes and different library implementations (inc debug to release) can mean runtime errors (crashes if you are lucky).
精彩评论