Thursday, July 22, 2010

Creating a UUID (universally unique identifier)

Most of my blogs are created because I spend too many hours searching, and trying to figure out how something works, and I don't want to do that again (if I need the same feature) and help other people to avoid the search and "experimentation".

What the problem was? I need a Universally unique identifier that works on *nix and Windows, so here's a piece of code I used in linux to create the uuid (this works without any problem):


uuid_t t;

char ch[36];
memset(ch, 0, 36);
uuid_unparse(t, ch);
string* uuid = new string(ch);

If you need the UUID in linux, use this sample and you will be ready in no time, it works flawless and does not depend on anything else than linux to run.

it's easy right? ok here's how I tried to achieve the same thing in Windows:

UUID uuid;
if (UuidCreate(&uuid) == 0) {
unsigned char* wszUuid = NULL;
UuidToString(&uuid, &wszUuid);
if (wszUuid != NULL) {
string* res = new string((char*)wszUuid);
return res;
} else {
return new string("");

That's the example I found in microsoft page, and some other blogs, but for some freaking reason the code does not compile... the error I'm getting is:

cannot convert `char**' to `short unsigned int**' for argument `2' to `RPC_STATUS UuidToString(UUID*, short unsigned int**)'

even when the signature is: "UuidToString(UUID*,unsigned char**)", (I know I'm not the smartest guy, but if the header says that the parameter is "unsigned char" why is keeping generating the error?), so after a few worthless hours looking around on internet and changing the definition to "short unsigned int*" and getting a Universally Unique Code with one letter... (yes... only 1 letter in the result) I changed my code to this:

QUuid uuid = QUuid::createUuid();
QString suuid = uuid.toString();

string res = suuid.toStdString();

// removes the { } characters
res = res.substr(1, res.size() - 2);
return new string(res);

And now is working in linux and windows, thanks to Qt project!

Btw, I hate to spend a lot of time looking for some simple feature, when you can use that time to create a full application from scratch.