Platform-independent GUID generation in C++?

后端 未结 6 1487
余生分开走
余生分开走 2020-12-02 10:27

What is the best way to programmatically generate a GUID or UUID in C++ without relying on a platform-specific tool? I am trying to make unique identifiers for objects in a

6条回答
  •  广开言路
    2020-12-02 11:00

    on linux: man uuid

    on win: check out for UUID structure and UuidCreate function in msdn

    [edit] the function would appear like this

    extern "C"
    {
    #ifdef WIN32
    #include 
    #else
    #include 
    #endif
    }
    
    std::string newUUID()
    {
    #ifdef WIN32
        UUID uuid;
        UuidCreate ( &uuid );
    
        unsigned char * str;
        UuidToStringA ( &uuid, &str );
    
        std::string s( ( char* ) str );
    
        RpcStringFreeA ( &str );
    #else
        uuid_t uuid;
        uuid_generate_random ( uuid );
        char s[37];
        uuid_unparse ( uuid, s );
    #endif
        return s;
    }
    

提交回复
热议问题