br-system 0.0.11

This is an System
Documentation
extern crate core_foundation;

use core_foundation::base::{TCFType};
use core_foundation::string::CFString;
use std::ptr;
use std::ffi::CStr;
use std::os::raw::c_char;

#[link(name = "IOKit", kind = "framework")]
extern "C" {
    pub fn IOServiceGetMatchingService(master_port: u32, matching: *mut std::ffi::c_void) -> u32;
    pub fn IOServiceMatching(name: *const c_char) -> *mut std::ffi::c_void;
    pub fn IORegistryEntryCreateCFProperty(
        entry: u32,
        key: *const std::ffi::c_void,
        allocator: *const std::ffi::c_void,
        options: u32,
    ) -> *const std::ffi::c_void;
    pub fn IOObjectRelease(obj: u32) -> i32;
}

pub fn get_uuid() -> Option<String> {
    unsafe {
        // 获取 IOService 匹配的字典
        let service_name = CStr::from_bytes_with_nul(b"IOPlatformExpertDevice\0").unwrap();
        let matching_dict = IOServiceMatching(service_name.as_ptr());

        if matching_dict.is_null() {
            return None;
        }

        // 获取设备服务
        let service = IOServiceGetMatchingService(0, matching_dict);
        if service == 0 {
            return None;
        }

        // 获取 IOPlatformUUID
        let key = CFString::new("IOPlatformUUID");
        let uuid_value = IORegistryEntryCreateCFProperty(service, key.as_concrete_TypeRef() as *const std::ffi::c_void, ptr::null(), 0);
        IOObjectRelease(service);

        if uuid_value.is_null() {
            return None;
        }

        // 将 CFTypeRef 转换为 CFString,并确保它是有效的 CFString
        let uuid_cfstring: CFString = TCFType::wrap_under_get_rule(uuid_value as *const _);

        // 将 CFString 转换为 Rust 字符串
        Some(uuid_cfstring.to_string())
    }
}