macOS Retrieve Hardware UUID

From Free Pascal wiki

What is a UUID?

A UUID (Universally Unique Identifier) is a 16-byte long number. It is normally expressed in a standard format of characters representing hexadecimal digits. UUIDs were formerly known as Globally Unique Identifiers (GUIDs), but are now officially Universally Unique Identifiers, or UUIDs, and are governed by Open Software Foundation, ISO/IEC, and IETF standards.

Demonstration code

A standalone program demonstrating the code necessary to retrieve an Apple Mac computer's hardware UUID is set out below.

program project1;
 
{$mode objfpc}{$H+}
{$modeswitch cvar}
{$linkframework IOKit}
 
uses
  ctypes, Classes, MacOSAll
  { you can add units after this };
 
type
  kern_return_t = cint; // if you use "integer" then you don't need "ctypes" unit
  natural_t = UInt32;
  mach_port_t = natural_t;
  io_object_t = mach_port_t;
  io_registry_entry_t = io_object_t;
 
 
  io_string_t = array [0..511] of ansichar;
  IOOptionBits = UInt32;
 
const
   kIOPlatformUUIDKey = 'IOPlatformUUID';
 
var
  kIOMasterPortDefault: mach_port_t; cvar; external;
 
function IORegistryEntryFromPath( masterPort: mach_port_t; const path: io_string_t): io_registry_entry_t; cdecl; external;
function IORegistryEntryCreateCFProperty(entry: io_registry_entry_t; key: CFStringRef;
    allocator: CFAllocatorRef; options: IOOptionBits): CFTypeRef; cdecl; external;
function IOObjectRelease(entry: io_registry_entry_t): kern_return_t; cdecl; external;
 
function get_platform_uuid: string;
var
  ioRegistryRoot : io_registry_entry_t;
  uuidCf         : CFStringRef;
  l : integer;
begin
  ioRegistryRoot := IORegistryEntryFromPath(kIOMasterPortDefault, 'IOService:/');
  uuidCf := CFStringRef (IORegistryEntryCreateCFProperty(ioRegistryRoot, CFSTR(kIOPlatformUUIDKey), kCFAllocatorDefault, 0));
  IOObjectRelease(ioRegistryRoot);
  SetLength(Result, 1024);
  CFStringGetCString(uuidCf, @Result[1], length(Result), kCFStringEncodingMacRoman);
  CFRelease(uuidCf);
  l:=StrLen(@Result[1]);
  SetLength(Result, l);
end;
 
begin
  writeln('get_platform_uuid: ', get_platform_uuid);
end.