<p>Most of my C/C++ development involves monolithic module files and absolutely no classes whatsoever, so usually when I need to make a <strong>DLL</strong> with accessible functions I just export them using the standard <code>__declspec(dllexport)</code> directive.  Then access them either dynamically via <code>LoadLibrary()</code> or at compile time with a header and lib file. </p>

<p>How do you do this when you want to export an entire class (and all it's public methods and properties)?</p>

<p>Is it possible to dynamically load that class at runtime and if so, how?</p>

<p>How would you do it with a header and lib for compile time linking?</p>

[{'answer_id': 28018, 'author': 'crashmstr', 'author_id': 1441, 'author_profile': 'https://Stackoverflow.com/users/1441', 'pm_score': 4, 'selected': False, 'text': "<p>I use some macros to mark the code for import or export</p>\n\n<pre>\n#ifdef ISDLL\n#define DLL __declspec(dllexport)\n#endif\n\n#ifdef USEDLL\n#define DLL __declspec(dllimport)\n#endif\n</pre>\n\n<p>Then declare the class in a header file:</p>\n\n<pre>\nclass DLL MyClassToExport { ... }\n</pre>\n\n<p>Then <code>#define ISDLL</code> in the libary, and <code>USEDLL</code> before including the header file in the place you want to use the class.</p>\n\n<p>I don't know if you might need to do anything differently for working with <code>LoadLibrary</code></p>\n"}, {'answer_id': 28022, 'author': 'Graeme Perrow', 'author_id': 1821, 'author_profile': 'https://Stackoverflow.com/users/1821', 'pm_score': 4, 'selected': False, 'text': '<p>When you build the DLL and the module that will use the DLL, have some kind of #define that you can use to distinguish between one and the other, then you can do something like this in your class header file:</p>\n\n<pre><code>#if defined( BUILD_DLL )\n    #define IMPORT_EXPORT __declspec(dllexport)\n#else\n    #define IMPORT_EXPORT __declspec(dllimport)\n#endif\nclass IMPORT_EXPORT MyClass {\n    ...\n};\n</code></pre>\n\n<p><em>Edit: crashmstr beat me to it!</em></p>\n'}, {'answer_id': 28289, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 5, 'selected': True, 'text': '<blockquote>\n  <p>What about late-binding? As in loading\n  it with LoadLibrary() and\n  GetProcAddress() ? I\'m used being able\n  to load the library at run time and it\n  would be great if you could do that\n  here.</p>\n</blockquote>\n\n<p>So there are two ways to load the DLL. The first is to reference one or more symbols from the DLL (your classname, for example), supply an appropriate import .LIB and let the linker figure everything out.</p>\n\n<p>The second is to explicitly load the DLL via LoadLibrary.</p>\n\n<p>Either approach works fine for C-level function exports. You can either let the linker handle it or call GetProcAddress as you noted.</p>\n\n<p>But when it comes to exported <strong>classes</strong>, typically only the first approach is used, i.e., implicitly link to the DLL. In this case the DLL is loaded at application start time, and the application fails to load if the DLL can\'t be found.</p>\n\n<p>If you want to link to a class defined in a DLL, and you want that DLL to be loaded dynamically, sometime after program initiation, you have two options:</p>\n\n<ol>\n<li><p>Create objects of the class using a special factory function, which internally will have to use (a tiny bit of) assembler to "hook up" newly created objects to their appropriate offsets. This has to be done at run-time AFTER the DLL has been loaded, obviously. A good explanation of this approach can be found <a href="http://www.codeproject.com/KB/DLL/classesexportedusingLL.aspx" rel="noreferrer">here</a>.</p></li>\n<li><p>Use a <a href="http://msdn.microsoft.com/en-us/library/151kt790.aspx" rel="noreferrer">delay-load DLL</a>.</p></li>\n</ol>\n\n<p>All things considered... probably better to just go with implicit linking, in which case you definitely want to use the preprocessor technique shown above. In fact, if you create a new DLL in Visual Studio and choose the "export symbols" option these macros will be created for you.</p>\n\n<p>Good luck...</p>\n'}, {'answer_id': 30162, 'author': 'Mat Noguchi', 'author_id': 1799, 'author_profile': 'https://Stackoverflow.com/users/1799', 'pm_score': 0, 'selected': False, 'text': "<p>If you're willing to put a vtable in the class you're exporting, you can export a function that returns an interface and implement the class in the .dll, then put that in the .def file. You might have to do some declaration trickery, but it shouldn't be too hard.</p>\n\n<p>Just like COM. :)</p>\n"}, {'answer_id': 7452230, 'author': 'Eli Bendersky', 'author_id': 8206, 'author_profile': 'https://Stackoverflow.com/users/8206', 'pm_score': 3, 'selected': False, 'text': '<p>Recently I asked myself exactly the same question, and summarized my findings <a href="http://eli.thegreenplace.net/2011/09/16/exporting-c-classes-from-a-dll/" rel="noreferrer">in a blog post</a>. You may find it useful.</p>\n\n<p>It covers exporting C++ classes from a DLL, as well as loading them dynamically with <code>LoadLibrary</code>, and discusses some of the issues around that, such as memory management, name mangling and calling conventions.</p>\n'}, {'answer_id': 24384693, 'author': 'SridharKritha', 'author_id': 1308589, 'author_profile': 'https://Stackoverflow.com/users/1308589', 'pm_score': 4, 'selected': False, 'text': '<p>Adding a simple working example for exporting a C++ class from a DLL :</p>\n\n<p>The given below example gives you only a short overview of how dll and exe can interact each other (self explanatory ) but it needs more things to add for changing into a production code. </p>\n\n<p>Full sample example is divided in to two part</p>\n\n<p><em>A. Creating a .dll library (MyDLL.dll)</em></p>\n\n<p><em>B. Creating an Application which uses .dll library (Application).</em></p>\n\n<p><strong>A. .dll project file (MyDLL.dll):</strong></p>\n\n<p><strong>1. dllHeader.h</strong></p>\n\n<pre><code>#ifdef  MYDLL_EXPORTS \n#define DLLCALL __declspec(dllexport)   /* Should be enabled before compiling \n                                           .dll project for creating .dll*/\n#else\n#define DLLCALL __declspec(dllimport)  /* Should be enabled in Application side\n                                          for using already created .dll*/\n#endif\n\n// Interface Class\nclass ImyMath {\npublic:\n    virtual ~ImyMath() {;}\n    virtual int Add(int a, int b) = 0;\n    virtual int Subtract(int a, int b) = 0;\n};\n\n// Concrete Class\nclass MyMath: public ImyMath {\npublic:\n    MyMath() {}\n    int Add(int a, int b);\n    int Subtract(int a, int b);\n    int a,b;\n};\n\n//  Factory function that will return the new object instance. (Only function\n//  should be declared with DLLCALL)\nextern "C" /*Important for avoiding Name decoration*/\n{\n    DLLCALL ImyMath* _cdecl CreateMathObject();\n};\n\n// Function Pointer Declaration of CreateMathObject() [Entry Point Function]\ntypedef ImyMath* (*CREATE_MATH) ();\n</code></pre>\n\n<p><strong>2. dllSrc.cpp</strong></p>\n\n<pre><code>#include "dllHeader.h"\n\n// Create Object\nDLLCALL ImyMath* _cdecl CreateMathObject() {\n    return new MyMath();\n}\n\nint MyMath::Add(int a, int b) {\n    return a+b;\n}\n\nint MyMath::Subtract(int a, int b) {\n    return a-b;\n}\n</code></pre>\n\n<p><strong>B. Application Project which load and link the already created .dll file:</strong></p>\n\n<pre><code> #include &lt;iostream&gt;\n#include &lt;windows.h&gt;\n#include "dllHeader.h"\n\nint main()\n{\n    HINSTANCE hDLL = LoadLibrary(L"MyDLL.dll"); // L".\\Debug\\MyDLL.dll"\n\n    if (hDLL == NULL) {\n        std::cout &lt;&lt; "Failed to load library.\\n";\n    }\n    else {\n        CREATE_MATH pEntryFunction = (CREATE_MATH)GetProcAddress(hDLL,"CreateMathObject");\n        ImyMath* pMath = pEntryFunction();\n        if (pMath) {\n            std::cout &lt;&lt; "10+10=" &lt;&lt; pMath-&gt;Add(10, 10) &lt;&lt; std::endl;\n            std::cout &lt;&lt; "50-10=" &lt;&lt; pMath-&gt;Subtract(50, 10) &lt;&lt; std::endl;\n        }\n        FreeLibrary(hDLL);\n    }\n    std::cin.get();\n    return 0;\n}\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/27998', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/194/']