21

我可以在 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

4 回答 4

27

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

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

于 2010-12-29T16:56:24.107 回答
13

bcsanches建议的解决方案

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

如果您要按照bcsanches的建议使用这种方法,请确保对您的对象使用以下函数,delete

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

始终成对定义此类函数,因为它确保您从创建它们的同一堆/内存池/等中删除对象。看到这对功能

于 2010-12-29T17:04:45.950 回答
5

您可以,并且您需要的所有信息都在此页面此页面上

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

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

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

于 2010-12-29T16:57:38.337 回答
2

如果您想在一个类中公开数据,上述解决方案不会削减它。您必须__declspec(dllexport)在 DLL 编译中对类本身添加 a,并__declspec(dllimport)在链接到 DLL 的模块中添加 a。

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

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

class MY_API MyClass {
   ...
};

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

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

于 2010-12-29T17:51:53.077 回答