I want to have multiple instances of a DLLInterface class but as each obje开发者_C百科ct will have pointers to the same DLL functions I want these to be static.
The below code doesn't compile. (I do have a reason for needing multiple instances containing the same pointers which the stripped down code below doesn't illustrate.)
//Header file:
typedef void (*DLLFunction)();
class DLLInterface
{
private:
static HINSTANCE hinstDLL;
public:
static DLLFunction Do;
DLLInterface()
{
if(!hinstDLL || !Do)
{
hinstDLL = LoadLibrary("DoubleThink.dll");
Do = (DLLFunction)GetProcAddress(hinstDLL, "Do");
}
}
};
I need to have all code contained within this header file also. (I know I can make it compile by adding statements like the following into a cpp file on the EXE but I need to avoid doing this.
HINSTANCE DLLInterface::hinstDLL = 0;
Thanks!
One trick I can think of is to use templates. The idea is you make the class the includes the static data a template class and then derive your actual class from it with some specific type:
template <class T>
class DLLInterfaceImpl;
{
private:
static HINSTANCE hinstDLL;
public:
static DLLFunction Do;
};
template <class T>
HINSTANCE DllInterfaceImpl<T>::hInstDLL;
template <class T>
DLLFunction DllInterfaceImpl<T>::Do;
class DllInterface : public DllInterfaceImpl<int>
{
};
Because DllInterfaceImpl is a template, you can put your static definitions in the header file and the compiler will do some "tricks" so that multiple definitions do not cause the link to fail.
精彩评论