从从模板继承的dll导出类

Exporting a class from a dll that inherits from a template

本文关键字:dll 继承      更新时间:2023-10-16

我正在从继承自模板基类的dll导出一个类。模板基类不是从dll导出的,而是这样设计的,即它在编译时像静态库一样链接。情况是这样的:

基类定义如下:

template<typename _type>
class Singleton
{
public:
    static void CreateSingleton(void);
    static _type* GetSingleton(void);
    static void DestroySingleton(void);
    virtual ~Singleton(void);
protected:
    Singleton(void);
    Singleton(const Singleton<_type> &copyfrom);
    _type* m_ptrSingleton;
};

我有一个从中继承的类,它被定义为:

#if defined(_ENGINE_EXPORT)
    #define ENGINELINKAGE __declspec(dllexport)
#elif defined(_ENGINE_IMPORT)
    #define ENGINELINKAGE __declspec(dllimport)
#else
    #define ENGINELINKAGE
#endif
class ENGINELINKAGE IWindowManager: public Singleton<IWindowManager>
{
public:
    virtual ~IWindowManager(void) =0;
};

我可以编译,但当试图在另一个从包含IWindowManager和Singleton的dll导入的项目中使用IWindowManager时,链接器会产生以下错误:

2>Engine_win32.obj : error LNK2019: unresolved external symbol "__declspec(dllimport) public: static class IWindowManager * __cdecl Singleton<class IWindowManager>::GetSingleton(void)" (__imp_?GetSingleton@?$Singleton@VIWindowManager@@@@SAPAVIWindowManager@@XZ) referenced in function "public: static class WindowManager_win32 * __cdecl WindowManager_win32::GetSingleton(void)" (?GetSingleton@WindowManager_win32@@SAPAV1@XZ)
2>WindowManager_win32.obj : error LNK2001: unresolved external symbol "__declspec(dllimport) public: static class IWindowManager * __cdecl Singleton<class IWindowManager>::GetSingleton(void)" (__imp_?GetSingleton@?$Singleton@VIWindowManager@@@@SAPAVIWindowManager@@XZ)
2>Window_win32.obj : error LNK2001: unresolved external symbol "__declspec(dllimport) public: static class IWindowManager * __cdecl Singleton<class IWindowManager>::GetSingleton(void)" (__imp_?GetSingleton@?$Singleton@VIWindowManager@@@@SAPAVIWindowManager@@XZ)
2>Engine_win32.obj : error LNK2019: unresolved external symbol "__declspec(dllimport) public: static void __cdecl Singleton<class IWindowManager>::DestroySingleton(void)" (__imp_?DestroySingleton@?$Singleton@VIWindowManager@@@@SAXXZ) referenced in function _main
2>Engine_win32.obj : error LNK2001: unresolved external symbol "protected: static class IWindowManager * Singleton<class IWindowManager>::m_ptrSingleton" (?m_ptrSingleton@?$Singleton@VIWindowManager@@@@1PAVIWindowManager@@A)

我已经定义了类,这样IWindowManager应该从dll导出,但Singleton不应该导出,而是在编译时静态链接到程序中。原因是,如果你想从dll中导出模板,而你没有一组你想要的特定模板实例,你必须静态链接它。不可能动态链接模板,但你必须动态链接你想要导出/导入的每个实例。

链接器错误似乎表明它正在尝试导出Singleton,尽管我没有指定应该导出它。

有人明白为什么会发生这种情况吗?或者我该如何解决?

如果类在DLL中,则必须在DLL中提供一些伪实例化。否则,将不会为singleton类生成任何代码。因此,以后的编译将失败,因为IWindowManager类将不在lib/DLL中。

Sidemark:您应该重新思考是否真的需要一个单独的