Hi,
I came across this article 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 Release()
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 std::auto_ptr<T>
-like class that calls the Release()
method before deleting the object.
I was wondering whether the following approach would work instead:
#include <memory>
#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<IXyz>( GetXyz_() )
Of course, GetXyz()
can be a global function defined in the header instead of a #define
. The advantage to this method would be that we don't need to cook up our own derivative of auto_ptr
that calls the Release()
method.
Thanks for your answers, Ashish.