【发布时间】:2020-02-20 08:51:59
【问题描述】:
我正在寻求帮助,以实现在 dll 库中正确释放内存。
我的项目结构如下:
库.dll:
- interface.h -> 使用纯虚方法定义基类
- implementation.h -> 从公共基类继承的派生类
- implementation.cpp -> 派生类方法定义
implementation.h 还包含导出的函数:
extern "C" __declspec(dllexport) Base* __stdcall Create()
{
return new Derived;
}
extern "C" __declspec(dllexport) void __stdcall Delete(Base* B)
{
delete B;
}
Appllication.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 定义不正确。如何解决这个问题?
我目前的解决方案是基于:
【问题讨论】:
标签: c++ dll smart-pointers dllimport dllexport