0

I am trying to create a Service Locator component and below is the implementation.

#ifndef __SERVICE_LOCATOR_H__
#define __SERVICE_LOCATOR_H__

#include <map>
using namespace std;


class ServiceLocator
{
    static map<string, void*> m_mapRegisteredTypes;

public:
    template<class T> static void Register(const T*);
    template<class T> static T* Resolve();

    virtual ~ServiceLocator() = 0;
};

ServiceLocator::~ServiceLocator(){}

map<string, void*> ServiceLocator::m_mapRegisteredTypes;

template<class T>
void ServiceLocator::Register(const T* object)
{
    ServiceLocator::m_mapRegisteredTypes[typeid(T).name()] = (void *)object;
}

template<class T>
T* ServiceLocator::Resolve()
{
    return (T*)ServiceLocator::m_mapRegisteredTypes[typeid(T).name()];
}

#endif /*__SERVICE_LOCATOR_H__*/

When I am trying to use it in two different DLLs, they are making thier own copy of ServiceLocator class. How can share static map<string, void*> m_mapRegisteredTypes across DLLs.

Anil8753
  • 2,663
  • 4
  • 29
  • 40

1 Answers1

0

In all of the dlls but one map<string, void*> ServiceLocator::m_mapRegisteredTypes should be declared extern. In this case, only one dll contains the definition of the member and all the others are dinamically linked to that one; consider the following example:

DLL1.cc:

//...
map<string, void*> ServiceLocator::m_mapRegisteredTypes();
//...

DLL2.cc, DLL3.cc, ...:

//...
extern map<string, void*> ServiceLocator::m_mapRegisteredTypes;
//...

DLL2,3,... should be linked dinamically to DLL1, so DLL1 will "provide the address" of the member.

Géza Török
  • 1,397
  • 7
  • 15