C++ 如何将Windows GUID转换为boost::uuid?

C++ 如何将Windows GUID转换为boost::uuid?,c++,boost,C++,Boost,我试图获取Windows GUID的字符串,但使用boost::uuid失败。结果正如这篇文章所说,字节顺序错误 void foo(GUID& g) { boost::uuids::uuid * u = reinterpret_cast<boost::uuids::uuid*>(&g); std::string ustr = boost::lexical_cast<std::string>(*u); } void foo(GUID&g) { bo

我试图获取Windows GUID的字符串,但使用
boost::uuid
失败。结果正如这篇文章所说,字节顺序错误

void foo(GUID& g)
{
  boost::uuids::uuid * u = reinterpret_cast<boost::uuids::uuid*>(&g);
  std::string ustr = boost::lexical_cast<std::string>(*u);
}
void foo(GUID&g)
{
boost::uuids::uuid*u=重新解释强制转换(&g);
std::string ustr=boost::词法转换(*u);
}
最后,我用这篇文章完成了我的转换

但我还是很好奇

  • 是否有一些优雅的方法可以将任何类型转换为boost
  • 如果有,是否有Windows的现成库
  • 即使你记下了地址,我想你还有其他麻烦。Microsoft在其
    GUID
    结构中使用双字和字,而Boost使用字节

    typedef struct _GUID {
        DWORD Data1;  WORD Data2;  WORD Data3;  BYTE Data4[8];
    } GUID;
    
    struct uuid
    {
        ...
    public:
        // or should it be array<uint8_t, 16>
        uint8_t data[16];
    };
    

    typedef struct _GUID {
        DWORD Data1;  WORD Data2;  WORD Data3;  BYTE Data4[8];
    } GUID;
    
    struct uuid
    {
        ...
    public:
        // or should it be array<uint8_t, 16>
        uint8_t data[16];
    };
    

    。。。结果正如这篇文章所说,字节顺序错误


    我认为目前接受的答案是不正确的。我相信Dutton的答案是正确的,但它没有显示UUID类型之间的典型转换。

    感谢@jww提出这个问题。我的好奇心是,MsToBoost看起来很丑。是否有一些优雅的转换方法?是否有现成的LIB供Windows升级类型covert?@Raymond-我找不到:。您找到的任何跨平台转换代码都将类似于上面的代码。例如,请参见Crypto++和Botan的。每个人都必须玩endian游戏。根据@jww修复了代码输入错误
    void MsToBoostUuid(const GUID& ms, boost::uuids::uuid& bst)
    {
        bst.data[0] = static_cast<uint8_t>(ms.Data1 >> 24);
        bst.data[1] = static_cast<uint8_t>(ms.Data1 >> 16);
        bst.data[2] = static_cast<uint8_t>(ms.Data1 >>  8);
        bst.data[3] = static_cast<uint8_t>(ms.Data1 >>  0);
    
        bst.data[4] = static_cast<uint8_t>(ms.Data2 >> 8);
        bst.data[5] = static_cast<uint8_t>(ms.Data2 >> 0);
    
        bst.data[6] = static_cast<uint8_t>(ms.Data3 >> 8);
        bst.data[7] = static_cast<uint8_t>(ms.Data3 >> 0);
    
        bst.data[8] = ms.Data4[0];
        bst.data[9] = ms.Data4[1];
        ...
        bst.data[14] = ms.Data4[6];
        bst.data[15] = ms.Data4[7];
    }
    
    void foo(const GUID& g)
    {
      boost::uuids::uuid u;
      MsToBoostUuid(g, u);
    
      std::string ustr = boost::lexical_cast<std::string>(*u);
    }
    
    inline bool operator==(const& uuid lhs, const GUID& rhs)
    {
        boost::uuids::uuid t;
        MsToBoostUuid(rhs, t);
        return std::equal(lhs.begin(), lhs.end(), t.begin());
    }
    
    inline bool operator==(const GUID& lhs, const& uuid rhs)
    {
        boost::uuids::uuid t;
        MsToBoostUuid(lhs, t);
        return std::equal(t.begin(), t.end(), rhs.begin());
    }