【问题标题】:DLL Import of pure virtual struct and unique_ptr can not compile due to Compressed_pair由于 Compressed_pa​​ir 导致纯虚拟结构和 unique_ptr 的 DLL 导入无法编译
【发布时间】:2019-01-11 17:06:45
【问题描述】:

我有两个项目,我的代码在一个项目中并作为 dll 导出,而导入项目是一个测试项目。最终,我想要一个 vtable,我也可以仅使用 struct 导入到 c 中。

我的纯虚拟结构是这样的:

#ifdef DLL_EXPORTS
#define MyAPI  __declspec( dllexport )
#else DLL_EXPORTS
#define MyAPI  __declspec( dllimport  )
#endif DLL_EXPORTS

struct MyAPI IVirtual
{
    virtual int GetNumber() = 0;
    virtual ~IVirtual() = 0;
};

MyAPI IVirtual * IVirtual_New(int);
MyAPI void IVirtual_Delete(IVirtual *);

这有一个 dll 的实现:

#include "Virtual.h"

struct Concrete : IVirtual
{
    int n;
    Concrete(int n) : n(n) { }
    virtual int GetNumber() { return n; }
    virtual ~Concrete() {}
};

IVirtual::~IVirtual() {}

MyAPI IVirtual * IVirtual_New(int n)
{
    auto that = new Concrete(n);
    return that;
}

MyAPI void IVirtual_Delete(IVirtual * that)
{
    auto fingerscrossed = static_cast<Concrete*>(that);
    delete fingerscrossed;
}

Test 项目导入 dll。共享指针测试编译并确认断言。

#include "CppUnitTest.h"
#include <memory>
#include <MyDLL/Virtual.h>

using namespace Microsoft::VisualStudio::CppUnitTestFramework;

namespace UsageTest
{       
    TEST_CLASS(UsageTest)
    {
    public:
        TEST_METHOD(SharedConstructor)
        {
            //looks ok - tests pass
            std::shared_ptr<IVirtual> sptr(IVirtual_New(4), IVirtual_Delete);
            Assert::AreEqual(4, sptr->GetNumber());
        }

        TEST_METHOD(UniqueConstructor)
        {
            std::unique_ptr<IVirtual, decltype(IVirtual_Delete)> uptr(IVirtual_New(6), IVirtual_Delete);
            Assert::AreEqual(6, uptr->GetNumber());
        }

    };
}

但是,当我添加 UniqueConstructor 方法时,测试项目停止编译。

C2207: 'std::_Compressed_pair<_Ty1,_Ty2,false>::_Myval1': a member of a class template cannot acquire a function type

我认为这与析构函数有关,但我无法确定那里到底发生了什么。

【问题讨论】:

  • this page 中的“类型要求”部分。
  • @HansPassant 我认为你是对的。我将类型从decltype(IVirtual_Delete) 更改为void(*)(IVirtual*)。为什么不是同一种类型?
  • @HansPassant 知道了 :) decltype(&amp;IVirtual_Delete)

标签: c++ unique-ptr dllexport pure-virtual


【解决方案1】:

今天该休息了。

decltype(&IVirtual_Delete) 

【讨论】:

    猜你喜欢
    • 2013-01-11
    • 2016-10-21
    • 1970-01-01
    • 2012-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-01
    相关资源
    最近更新 更多