using System; using System.Runtime.InteropServices; using static flecs_hub.flecs; using static flecs_hub.flecs.Runtime; namespace gaemstone.Utility; public unsafe static class CStringExtensions { public static CString Empty { get; } = (CString)""; public static CString ETX { get; } = (CString)"\x3"; // TODO: Temporary, until flecs supports Empty. public static unsafe byte[]? FlecsToBytes(this CString str) { if (str.IsNull) return null; var pointer = (byte*)(nint)str; // Find length of the string by locating the NUL character. var length = 0; while (true) if (pointer[length++] == 0) break; // Create span over the region, NUL included, copy it into an array. return new Span(pointer, length).ToArray(); } public static byte[]? FlecsToBytesAndFree(this CString str) { var result = str.FlecsToBytes(); str.FlecsFree(); return result; } public static string? FlecsToString(this CString str) => Marshal.PtrToStringUTF8(str); public static string? FlecsToStringAndFree(this CString str) { var result = str.FlecsToString(); str.FlecsFree(); return result; } public static void FlecsFree(this CString str) { if (!str.IsNull) ecs_os_get_api().free_.Data.Pointer((void*)(nint)str); } }