如何使用从DLL导出的类

How to use exported class from DLL

本文关键字:DLL 何使用      更新时间:2023-10-16

嘿,我正试图编写一个游戏引擎,我试图导出Dll中的一个类,并试图在我的主代码中使用它。类似于使用loadlibrary()函数。我知道如何将函数导出到Dll和从Dll中使用函数。但我想导出类,然后像使用函数一样使用它们。我不想为那个类include <headers>然后使用它。我希望它是运行时的。我有一个非常简单的类的以下代码,我用它来进行实验

#ifndef __DLL_EXP_
#define __DLL_EXP_
#include <iostream>
#define DLL_EXPORT __declspec(dllexport)
class ISid
{
public:
virtual void msg() = 0;
};
class Sid : public ISid
{
void msg()
{
    std::cout << "hkjghjgulhul..." << std::endl;
}
};
ISid DLL_EXPORT *Create()
{
return new Sid();
}
void DLL_EXPORT Destroy(ISid *instance)
{
   delete instance;
}
#endif

如何在我的主代码中使用它?任何帮助都将不胜感激。如果重要的话,我会使用Visual Studio 2012。

如果我理解问题不是你不知道如何加载类,但无法想象之后如何使用它?我无法帮助语法,因为我习惯于共享对象动态加载,而不是dll,但用例如下:

// isid.h that gets included everywhere you want to use Sid instance
class ISid
{
public:
    virtual void msg() = 0;
};

如果你想使用动态加载的代码,你仍然需要知道它的接口。这就是为什么我建议你把接口移到一个常规的非dll头

// sid.h
#ifndef __DLL_EXP_
#define __DLL_EXP_
#include <iostream>
#include "isid.h" // thus you do not know what kind of dll you are loading, but you are well aware of the interface
#define DLL_EXPORT __declspec(dllexport)
class Sid : public ISid
{
void msg()
{
    std::cout << "hkjghjgulhul..." << std::endl;
}
};
ISid DLL_EXPORT *Create()
{
    return new Sid();
}
void DLL_EXPORT Destroy(ISid *instance)
{
    delete instance;
}
#endif

然后你做这样的事情:

// main.cpp
#include <sid.h>
int main()
{
 // windows loading magic then something like where you load sid.dll
.....
typedef ISid* (*FactoryPtr)();
FactoryPtr maker = (FactoryPtr) dlsym(symHanlde, "Create");
ISid* instance = (*maker)();
instance->msg();
...
}

很抱歉,我不能提供dll代码,但我现在不想学习windows dll接口,所以我希望这有助于理解我的评论。