From ff08a76eac57c4f085faf93d68e1eb460983a425 Mon Sep 17 00:00:00 2001 From: Patrick Dawson Date: Mon, 9 Sep 2024 07:31:54 +0200 Subject: [PATCH] Use UnsafeAccessor to call internal Rid constructor without reflection --- addons/imgui-godot/ImGuiGodot/Internal/Util.cs | 11 +++-------- doc/test/csbench/BenchRid.cs | 10 ++++++++++ 2 files changed, 13 insertions(+), 8 deletions(-) diff --git a/addons/imgui-godot/ImGuiGodot/Internal/Util.cs b/addons/imgui-godot/ImGuiGodot/Internal/Util.cs index 2575e32..8a204aa 100644 --- a/addons/imgui-godot/ImGuiGodot/Internal/Util.cs +++ b/addons/imgui-godot/ImGuiGodot/Internal/Util.cs @@ -1,15 +1,10 @@ using Godot; -using System; -using System.Runtime.InteropServices; +using System.Runtime.CompilerServices; namespace ImGuiGodot.Internal; internal static class Util { - public static Rid ConstructRid(ulong id) - { - ReadOnlySpan uspan = new(in id); - ReadOnlySpan bytes = MemoryMarshal.Cast(uspan); - return MemoryMarshal.Read(bytes); - } + [UnsafeAccessor(UnsafeAccessorKind.Constructor)] + public static extern Rid ConstructRid(ulong id); } diff --git a/doc/test/csbench/BenchRid.cs b/doc/test/csbench/BenchRid.cs index a04ccb7..0264176 100644 --- a/doc/test/csbench/BenchRid.cs +++ b/doc/test/csbench/BenchRid.cs @@ -2,6 +2,7 @@ using System.Reflection.Emit; using System.Reflection; using System.Runtime.InteropServices; +using System.Runtime.CompilerServices; namespace csbench; @@ -58,6 +59,15 @@ public Rid ConstructRid_MemoryMarshal_SpanCast() return MemoryMarshal.Read(bytes); } + [Benchmark] + public Rid ConstructRid_UnsafeAccessor() + { + return RidConstructor(_id); + } + + [UnsafeAccessor(UnsafeAccessorKind.Constructor)] + private static extern Rid RidConstructor(ulong id); + [Benchmark(Baseline = true)] public unsafe Rid ConstructRid_Unsafe_DirectCopy() {