c++ - boost 不透明类型的序列化

标签 c++ boost boost-serialization

我希望能够序列化 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
        ]

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

谢谢

最佳答案

HANDLE 是在 winnt.h 中定义的特定于 Windows API 的数据类型。根据MSDN ,

A handle to an object. This type is declared in WinNT.h as follows:

typedef PVOID HANDLE;

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

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

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

现在,如果您真的不想这样做——您肯定您想要指针值——也许尝试在通过reinterpret_caststd::intptr_tstd::uintptr_t(因为 可能 在 C++ 的 cstdint 中定义11).

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

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

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

关于c++ - boost 不透明类型的序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12342956/

相关文章:

android - 编译时使用 Boost for Android 会抛出错误

c++ - BOOST_STATIC_ASSERT_MSG - 缺少错误信息

c++ - boost::serialization - 是否有一种可移植的方式来二进制序列化 std::wstrings?

c++ - 在命名管道和套接字之间进行简单切换的 IPC

c++ - 尝试使用 Boost 序列化库时出错

c++ - LevelDB 与 std::map

c++ - Hessian 最小阈值对 SurfFeatureDetector 函数意味着什么?

c++ - ifstream无限循环(它似乎永远找不到停止读取的标记)

c++ - 为什么 snprintf 在打印单个数字时始终比 ostringstream 快 2 倍?

c++ - 如何拥有一个 unordered_map,其中值类型是它所在的类?