title: Exporting C++ classes from DLL
body: <p>I came across this <a href="http://www.codeproject.com/KB/cpp/howto_export_cpp_classes.aspx#CppMatureApproach" rel="nofollow noreferrer">article</a> on Code Project that talks about using an abstract interface as an alternative to exporting an entire class from a C++ DLL to avoid name mangling issues. The author has a <code>Release()</code> method in his interface definition that is supposed to be called by the user to free the class object's resources after using it. To automate the calling of this method the author also creates an <code>std::auto_ptr&lt;T&gt;</code>-like class that calls the <code>Release()</code> method before deleting the object.</p>
  
  <p>I was wondering whether the following approach would work instead:</p>
  
  <pre><code>#include &lt;memory&gt;
  
  #if defined(XYZLIBRARY_EXPORT) // inside DLL
  #   define XYZAPI   __declspec(dllexport)
  #else // outside DLL
  #   define XYZAPI   __declspec(dllimport)
  #endif  // XYZLIBRARY_EXPORT
  
  // The abstract interface for Xyz object.
  // No extra specifiers required.
  struct IXyz
  {
      virtual int Foo(int n) = 0;
  
      //No Release() method, sub-class' destructor does cleanup
      //virtual void Release() = 0;
  
      virtual ~IXyz() {}
  };
  
  // Factory function that creates instances of the Xyz object.
  // Private function, do not use directly
  extern "C" XYZAPI IXyz* __stdcall GetXyz_();
  
  #define GetXyz()      std::auto_ptr&lt;IXyz&gt;( GetXyz_() )
  </code></pre>
  
  <p>Of course, <code>GetXyz()</code> can be a global function defined in the header instead of a <code>#define</code>. The advantage to this method would be that we don't need to cook up our own derivative of <code>auto_ptr</code> that calls the <code>Release()</code> method.</p>
  
  <p>Thanks for your answers,
  Ashish.</p>