Friday, February 27, 2009

[VC++] Creating Unique ID with CoCreateGuid()

At some point of a programmers life he will be in need to create some unique name. For example in one of my previous post for Preventing Multiple Instances I have suggested using a unique name for the mutex. Here is a utility function which will help you create a unique string.
// Return Unique String ID each time
const CString CreateUniquieID()
{
GUID UIDObj;
// Create Unique ID
CoCreateGuid( &UIDObj );
unsigned char* pUIDStr;
// Convert Unique ID to String
UuidToString( &UIDObj, &pUIDStr );
CString csUIDStr( pUIDStr );
// Free allocated string memory
RpcStringFree( &pUIDStr );
return csUIDStr;
}
This function uses CoCreateGuid() function which create an absolutely unique number that we can use as a persistent identifier. UuidToString () is used convert this Unique ID to a string. Do not forget to call RpcStringFree() for deallocating the memory if you are calling UuidToString (). You may need to include Rpc.h and link to Rpcrt4.lib for building the function.

4 comments:

Anonymous said...

Me sirvio. Muchas gracias !!!!

Anonymous said...

Thank you very much for intelligent solution.

Anonymous said...

ps.y@hotmail.de

says;-

Fuck Islam, fuck Mohammed, fuck Rourou

you will never find me

elia said...

RpcStringFree fails with:

Error 24 error C2664: 'RpcStringFreeW' : cannot convert parameter 1 from 'unsigned char **' to 'RPC_WSTR *' c:\users\elia\documents\work\softpublisher\svn\powerfox\xpcom\vs proj\powerfoxdll\powerfoxdll\powerfoxdll.cpp 1141 1 PowerFoxDll