1

我希望能够序列化一个 Windows HANDLE:

typedef void *HANDLE

如果我尝试使用以下方法进行编译:

struct Foo
{
    HANDLE file;

protected:
    friend class boost::serialization::access;

    template<class Archive>
    void serialize(Archive & ar, const unsigned int /*version*/)
    {
        ar & file;
    }
};

我得到编译错误:

c:\projects\3rdparty\src\boost\include\boost/mpl/print.hpp(51) : warning C4308: negative integral constant converted to unsigned type
        c:\projects\3rdparty\src\boost\include\boost/serialization/static_warning.hpp(92) : see reference to class template instantiation 'boost::mpl::print<T>' being compiled
        with
        [
            T=boost::serialization::BOOST_SERIALIZATION_STATIC_WARNING_LINE<98>
        ]
        c:\projects\3rdparty\src\boost\include\boost/archive/detail/check.hpp(98) : see reference to class template instantiation 'boost::serialization::static_warning_test<B,L>' being compiled
        with
        [
            B=false,
            L=98
        ]
        c:\projects\3rdparty\src\boost\include\boost/archive/detail/oserializer.hpp(313) : see reference to
function template instantiation 'void boost::archive::detail::check_object_tracking<T>(void)' being compiled
        with
        [
            T=Foo
        ]
        c:\projects\3rdparty\src\boost\include\boost/archive/detail/oserializer.hpp(525) : see reference to
function template instantiation 'void boost::archive::detail::save_non_pointer_type<Archive>::invoke<T>(Archive &,T &)' being compiled
        with
        [
            Archive=boost::archive::text_oarchive,
            T=Foo
        ]

但是,如果我更改fileint,一切都很好。如何告诉 boost 将 HANDLE 序列化为整数?

谢谢

4

2 回答 2

4

HANDLE是在winnt.h. 根据MSDN

对象的句柄。该类型声明WinNT.h如下:

typedef PVOID HANDLE;

所以,现在我们看到它HANDLE实际上只是void *——代表一个对象的句柄。想想你想要做什么;在 Windows API 中序列化指向某个对象的指针有意义吗?

相反,尝试序列化检索等价物所需的内容HANDLE;从成员的名字来看,我猜你用过CreateFile——所以,你需要知道......

  • 文件名
  • 所需的访问权限(例如GENERIC_READ | GENERIC_WRITE
  • 共享模式(例如FILE_SHARE_DELETE
  • 可选地,安全属性
  • 创作倾向(即CREATE_NEW,TRUNCATE_EXISTING等)
  • 文件或设备标志和属性
  • (可选)模板文件——用于在创建文件时复制其属性

现在,如果你真的不想这样做——你肯定你想要指针值——也许在通过reinterpret_castto std::intptr_tor转换之后尝试序列化它std::uintptr_t可能cstdint在C++11中定义)。

ar & reinterpret_cast<std::intptr_t>(file);

...那么您应该将其与以下内容结合起来(反序列化时):

std::intptr_t _file;
ar & _file;
HANDLE file = std::reinterpret_cast<HANDLE>(_file);
于 2012-09-09T21:09:31.667 回答
0

最终通过拆分序列化来解决问题。虽然看起来像一个黑客:

struct Foo
{
    HANDLE file;

protected:
    friend class boost::serialization::access;

    template<class Archive>
    void save(Archive & ar, const unsigned int /*version*/) const
    {
        unsigned int _file = reinterpret_cast<unsigned int>(file);
        ar & _file;
    }

    template<class Archive>
    void load(Archive & ar, const unsigned int /*version*/)
    {
        unsigned int _file;
        ar & _file;
        file = reinterpret_cast<HANDLE>(_file);
    }
    BOOST_SERIALIZATION_SPLIT_MEMBER()
};
于 2012-09-09T22:44:40.837 回答