Showing posts with label COM. Show all posts
Showing posts with label COM. Show all posts

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.