嘿,我正在尝试编写一个游戏引擎,我试图在 Dll 中导出一个类,并试图在我的主代码中使用它。喜欢使用 loadlibrary()
功能。我知道如何向 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;
};
如果你想使用动态加载的代码,你还是得知道它的接口(interface)。这就是为什么我建议您将接口(interface)移动到常规的非 dll header 中
// 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 接口(interface),所以我希望这有助于理解我的评论。
关于c++ - 如何使用从 DLL 导出的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20160430/