2013-11-23 45 views
0

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

#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.

+0

http://stackoverflow.com/questions/110833/dynamically-importing-ac-class-from-a-dll – user2176127

+0

虽然上面的线程很好,简而言之,您可以将接口类从dll中取出一个单独的头文件,然后通过分配给创建实例的基指针调用方法。 – 2013-11-23 11:20:37

+0

其中的解决方案显示了如何从Dll加载函数,我已经知道了。我无法理解如何加载课程。我不知道如何加载该Create函数,因为在为此创建typdef时,我需要返回类型,但我不想包含标题。 – Xk0nSid

回答

1

如果我明白问题不是你不知道如何加载类,但不能完全想象如何使用它之后呢?我不能与语法帮助,因为我习惯了共享对象的动态加载,而不是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界面,所以我希望这有助于理解我的评论。

+0

在Windows中,您可以使用'LoadLibrary'动态加载库,并通过'GetProcAddress'获取导出函数的地址。 – user2176127

+0

非常感谢您的帮助。我只是试图找到一种方法,而不必包含头文件“isid.h”。没有那个,猜猜不能做到。但是,无论如何感谢它确实有帮助。 – Xk0nSid