从DLL中删除类的实例



我请求帮助在dll库中实现正确的内存释放。

我的项目结构如下:

Library.dll:

  • interface.h->具有纯虚拟方法的基类定义
  • implementation.h->从公共库继承的派生类
  • implementation.cpp->派生类方法定义

实现.h还包含导出的函数:

extern "C" __declspec(dllexport) Base* __stdcall Create()
{
return new Derived;
}
extern "C" __declspec(dllexport) void __stdcall Delete(Base* B)
{
delete B;
}

Apllication.exe代码如下所示:

#include "interface.h"
#include "windows.h"
#include <iostream>
#include <memory>
typedef Base* (*CREATE_BASE)();
std::unique_ptr<Base> SmartPointer;
int main()
{
// Load the DLL
HINSTANCE dll_handle = ::LoadLibrary(TEXT("Library.dll"));
if (!dll_handle) {
std::cout << "Unable to load DLL!n";
return 1;
}
// Get the function from the DLL
CREATE_BASE Fn = (CREATE_BASE)GetProcAddress(dll_handle, "Create");
if (!Fn) {
std::cout << "Unable to load Create from DLL!n";
::FreeLibrary(dll_handle);
return 1;
}
// i have possibility to use only C++11 so creation of unique_ptr looks like this:
SmartPointer = std::unique_ptr<Base>(Fn());
// ... do something like SmartPointer->Action();
::FreeLibrary(dll_handle);
return 0;
}

上面的代码很有效,我可以很容易地初始化Base对象并从Derived类执行函数。现在我想使用导出的"Delete"函数作为自定义指针删除器。所以我准备了类型的定义:

typedef void (*DELETE_BASE)(Base* B);

我想或多或少这样使用它:

DELETE_BASE DeleteFn=(DELETE_BASE)GetProcAddress(dll_handle,"Delete");
SmartPointer = std::unique_ptr<Base>(Fn(),DeleteFn);

但是,我得到一个编译器错误,这个unique_ptr定义不正确。如何解决此问题?

我目前的解决方案基于:

  • 如何在dll中创建shared_ptr并通过工厂函数导出

由于要覆盖默认的deleter,因此必须指定deleter函数的类型(请参阅std::unique_ptr<>(。

您使用过的位置:

std::unique_ptr<Base>

你会想要使用:

std::unique_ptr<Base, DELETE_BASE>

最新更新