如何在DLL中使用类?

时间:2010-12-29 16:46:09

标签: c++ class dllimport dllexport

我可以在DLL中放一个类吗? 我写的课是这样的:

    class SDLConsole
{
      public:
             SDLConsole();
             ~SDLConsole(){};
             void getInfo(int,int);
             void initConsole(char*, char*, SDL_Surface*, int, int, int);
             void sendMsg(char*,int, SDL_Surface*);
             void cls(SDL_Surface*);

      private:
              TTF_Font *font;
              SDL_Surface *consoleImg;
              int width, pos, height, line, size, ctLine;
              SDL_Surface* render(char*,int);

};

我知道如何加载DLL并在DLL中使用该函数,但是如何在DLL中放置一个类?非常感谢你。

4 个答案:

答案 0 :(得分:25)

如果使用运行时动态链接(使用LoadLibrary加载dll),则无法直接访问该类,需要为类声明一个接口并创建一个返回此类实例的函数,如下所示: / p>

class ISDLConsole
{
  public:             
         virtual void getInfo(int,int) = 0;
         virtual void initConsole(char*, char*, SDL_Surface*, int, int, int) = 0;
         virtual void sendMsg(char*,int, SDL_Surface*) = 0;
         virtual void cls(SDL_Surface*) = 0;
 };

 class SDLConsole: public ISDLConsole
 {
    //rest of the code
 };

 __declspec(dllexport) ISDLConsole *Create()
 {
    return new SDLConsole();
 }

否则,如果您在加载期间链接dll,只需使用icecrime提供的信息:http://msdn.microsoft.com/en-us/library/a90k134d.aspx

答案 1 :(得分:13)

bcsanches

建议

Solution

 __declspec(dllexport) ISDLConsole *Create()
 {
    return new SDLConsole();
 }

如果您要通过 bcsanches 将此方法用作suggested,请确保使用以下函数delete您的对象,

 __declspec(dllexport) void Destroy(ISDLConsole *instance)
 {
       delete instance;
 }

在对中定义始终这样的函数,因为它确保您从创建它们的同一堆/内存池/等中删除对象。见pair-functions

答案 2 :(得分:5)

您可以,所需的所有信息都在this pagethis page上:

#ifdef _EXPORTING
   #define CLASS_DECLSPEC __declspec(dllexport)
#else
   #define CLASS_DECLSPEC __declspec(dllimport)
#endif

class CLASS_DECLSPEC SDLConsole
{
    /* ... */
};

剩下的就是在构建DLL时定义预处理器符号_EXPORTING

答案 3 :(得分:2)

如果要在类中公开数据,上述解决方案不会削减它。你必须在DLL编译中对类本身打一个__declspec(dllexport),并在模块中绑定一个__declspec(dllimport)

一种常见的技术是这样做(Microsoft向导生成这样的代码):

#ifdef EXPORT_API
#define MY_API __declspec(dllexport)
#else
#define MY_API __declspec(dllimport)
#endif

class MY_API MyClass {
   ...
};

然后确保在DLL项目中定义EXPORT_API,并确保它未在链接到DLL的模块中定义。

如果从头开始在Visual C ++中创建一个新的DLL项目,并选中“导出符号”复选框,则会使用此技术生成一些示例代码。

相关问题