How to implement a Singleton in an application with DLL

前端 未结 3 1424
闹比i
闹比i 2021-01-22 05:14

I have an application (in MS Visual Studio) that contains 3 projects:

  • main (the one that contains the main function)
相关标签:
3条回答
  • 2021-01-22 05:50

    When I ran into this same problem I solved it by creating another DLL whose sole purpose is to manage the singleton instance. All attempts to get a pointer to the singleton call the function inside this new DLL.

    0 讨论(0)
  • 2021-01-22 06:07

    You can decide where singleton should reside and then expose it to other consumers.


    Edited by OP:

    For example, i want that the config instance appear only in the EXE (not DLL).

    1. Turn the instance into a pointer

      static Config* g_instance;
      
    2. Add a separate initializing function to device's exported functions:

      void InitializeWithExisting(Config* instance) {g_instance=instance;}
      
    3. After initializing the singleton normally, use the second initialization:

      Config::Initialize();
      Config::InitializeWithExisting();
      
    0 讨论(0)
  • 2021-01-22 06:14

    I believe that defining and accessing singleton instance this way might solve your problem:

    Config& getInstance()
    {
      static Config config;
      return config;
    }
    

    This way you also don't need to have (and call) the Initialize method, you can use constructor for initializing, that will be called automatically when you call getInstance for the first time.

    0 讨论(0)
提交回复
热议问题