Page 1 of 1

Guid - generate, convert(string to struct / struct to string

Posted: 07 May 2015, 09:16
by Coco
Simple lib to manage creation and conversion(to/from string) of GUID/CLSID. Related: jNizM's Class & Func GUID / UUID

Create/generate GUID:
oGuid := Guid_New()
  • To retrieve the address of the GUID structure:
    pGuid := oGuid.Ptr OR pGuid := oGuid[]
  • To retrieve the string representation of the GUID:
    sGuid := oGuid.Str
Existing GUID(string or struct):
  • String to GUID struct:
    pGuid := Guid_FromStr( sGuid, ByRef VarOrAddress )
  • GUID struct to string:
    sGuid := Guid_ToStr( ByRef VarOrAddress )
Source (or @GitHub):

Code: Select all

Guid_New()
{
	return new __GUID
}

Guid_FromStr(sGuid, ByRef VarOrAddress)
{
	if IsByRef(VarOrAddress) && (VarSetCapacity(VarOrAddress) < 16)
		VarSetCapacity(VarOrAddress, 16) ; adjust capacity
	pGuid := IsByRef(VarOrAddress) ? &VarOrAddress : VarOrAddress
	if ( DllCall("ole32\CLSIDFromString", "WStr", sGuid, "Ptr", pGuid) < 0 )
		throw Exception("Invalid GUID", -1, sGuid)
	return pGuid ; return address of GUID struct
}

Guid_ToStr(ByRef VarOrAddress)
{
	pGuid := IsByRef(VarOrAddress) ? &VarOrAddress : VarOrAddress
	VarSetCapacity(sGuid, 78) ; (38 + 1) * 2
	if !DllCall("ole32\StringFromGUID2", "Ptr", pGuid, "Ptr", &sGuid, "Int", 39)
		throw Exception("Invalid GUID", -1, Format("<at {1:p}>", pGuid))
	return StrGet(&sGuid, "UTF-16")
}

class __GUID ; naming convention to avoid possible variable name conflict (global namespace)
{
	__Get(key:="", args*)
	{
		if (key == "") || (key = "Ptr") || (key = "Str")
		{
			if !pGuid := ObjGetAddress(this, "_GUID")
			{
				ObjSetCapacity(this, "_GUID", 94) ; 16 + (39 * 2)
				pGuid := ObjGetAddress(this, "_GUID")
				if ( DllCall("ole32\CoCreateGuid", "Ptr", pGuid) != 0 )
					throw Exception("Failed to create GUID", -1, Format("<at {1:p}>", pGuid))

				DllCall("ole32\StringFromGUID2", "Ptr", pGuid, "Ptr", pGuid + 16, "Int", 39)
			}
			return InStr("Ptr", key) ? pGuid : StrGet(pGuid + 16, "UTF-16")
		}
	}
}

Re: Guid - generate, convert(string to struct / struct to st

Posted: 07 May 2015, 09:30
by jNizM
Did something simliar few month ago :P
Class Globally unique identifier (GUID) / Universally unique identifier (UUID)

Was my first try with Classes ^^

( I need to rewrite many old codes from me -.- )

Re: Guid - generate, convert(string to struct / struct to st

Posted: 07 May 2015, 09:57
by Coco
I was actually using your CreateGUID() function :). Then I needed something that would allow me to retrieve the struct as well (CLSIDFromString) and also something that would allow me to work with existing(retrieved from file or something) GUIDs(string or struct).