C ++一个单例类与dll [英] C++ a singleton class with dll
问题描述
我用类创建了一个静态库:
I created a static library with class:
class CLog
{
private:
CLog();
...
...
public:
static CLog& GetInstance()
{
static CLog Instance;
return Instance;
}
void Write(char *cpPr);
};
#define Log CLog::GetInstance()
此库链接到dll,主程序。 dll由LoadLibrary加载。在这种情况下,很明显,在主exe和dll中调用Log.Write,创建两个单独的CLog实例。任何想法如何解决这个问题,仍然提供动态加载dll?
This library is linked to a dll and a main program. The dll is loaded by LoadLibrary. In this case is obvious that calling Log.Write in a main exe and in dll, creates two separate instances of CLog. Any ideas how to work around this issue and still provide dynamic loading a dll?
推荐答案
问题是,静态库,无论是主程序还是DLL,都会得到一个单独的静态变量副本。这打破了创建单例的典型方法。
The problem is that every project that links the static library, be it main program or DLL, will get a separate copy of the static variable. This breaks the typical method of creating a singleton.
最简单的方法是创建另一个包含单例的DLL,而不是静态库。因为只有一个链接器输出将包含静态变量,所以问题就解决了。
The simplest way around this is to create another DLL which holds the singleton, rather than a static library. Since only one linker output will contain the static variable, the problem is solved.
在我自己的例子中,我创建了一个singleton管理器,只有一个副本存在应用程序。单例管理器存在为它自己的DLL。
In my own case I created a singleton manager that identified each singleton by a unique GUID and ensured that only one copy existed application wide. The singleton manager existed as its own DLL.
这篇关于C ++一个单例类与dll的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!