如何在DLL中使用类?

r1c*_*ank 19 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);

};
Run Code Online (Sandbox Code Playgroud)

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

bcs*_*hes 25

如果使用运行时动态链接(使用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();
 }
Run Code Online (Sandbox Code Playgroud)

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

  • 因为只有v-table布局必须在库和客户端之间匹配,这相对容易实现,甚至在不同语言之间.另一方面,使用`__declspec(dllexport)`一切都必须匹配:编译器供应商,编译器版本,编译选项,否则您将最终遇到名称错位(链接错误)或单定义规则违规相应的崩溃. (5认同)
  • 最终,您必须使用编译器的X版编译应用程序,因为这是库A使用的.然后你想使用库B,但你不能,因为它需要编译器的版本Y. (3认同)
  • 也许COM(组件对象模型)在这个答案中值得一提,因为它的工作方式几乎相同:入口点函数叫做"DllGetClassObject",你只接收接口指针. (2认同)

Naw*_*waz 13

bcsanches建议的解决方案,

 __declspec(dllexport) ISDLConsole *Create()
 {
    return new SDLConsole();
 }
Run Code Online (Sandbox Code Playgroud)

如果你打算使用这种方法作为建议bcsanches,然后确保你使用下面的函数来delete你的对象,

 __declspec(dllexport) void Destroy(ISDLConsole *instance)
 {
       delete instance;
 }
Run Code Online (Sandbox Code Playgroud)

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


ice*_*ime 5

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

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

class CLASS_DECLSPEC SDLConsole
{
    /* ... */
};
Run Code Online (Sandbox Code Playgroud)

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

  • 这不是"剩下的一切".您还需要确保使用相同的编译器来构建DLL和所有客户端,编译器选项也匹配.对于以这种方式执行操作,您需要付出巨大的可维护性惩罚,[bcsanches建议的纯虚拟接口](http://stackoverflow.com/questions/4555961/how-to-use-a-class-in-dll/4556025 #4556025)好多了. (2认同)