我遇到了这个 article在 Code Project 上讨论了使用抽象接口(interface)作为从 C++ DLL 导出整个类的替代方法以避免名称混淆问题。作者有Release()
他的接口(interface)定义中的方法应该由用户调用以在使用后释放类对象的资源。为了自动调用此方法,作者还创建了一个 std::auto_ptr<T>
-like 调用 Release()
的类删除对象之前的方法。
我想知道以下方法是否可行:
#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_() )
当然,GetXyz()
可以是 header 中定义的全局函数而不是 #define
.这种方法的优点是我们不需要编写我们自己的 auto_ptr
的导数。调用 Release()
方法。
感谢您的回答, 阿希什。
最佳答案
通过这样做,您冒着调用 delete(在您的进程中,在 auto_ptr 的析构函数中)的风险,该对象不是由对 new() 的匹配调用创建的(在工厂函数内部完成,因此在 dll 内部完成)。肯定会出现问题,例如,当您的 dll 在 Release模式下编译而调用进程处于 Debug模式时。
Release() 方法更好。
关于c++ - 从 DLL 导出 C++ 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3206578/