从DLL删除类的实例

问题描述 投票:0回答:1

我正在寻求帮助来实现dll库中适当的内存释放。

我的项目结构如下:

Library.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;
}

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定义不正确的编译器错误。如何解决?

我当前的解决方案基于:

c++ dll smart-pointers dllimport dllexport
1个回答
0
投票

由于要覆盖默认删除程序(请参考std::unique_ptr<>,因此必须指定删除程序功能的类型。

您使用过的地方:

std::unique_ptr<Base>

相反,您想使用:

std::unique_ptr<Base, DELETE_BASE>
© www.soinside.com 2019 - 2024. All rights reserved.