From f4e879a1e6ad810aa38c1c020467a2589441871b Mon Sep 17 00:00:00 2001 From: Mary-nyan Date: Thu, 24 Nov 2022 15:26:29 +0100 Subject: Reduce usage of Marshal.PtrToStructure and Marshal.StructureToPtr (#3805) * common: Make BinaryReaderExtensions Read & Write take unamanged types This allows us to not rely on Marshal.PtrToStructure and Marshal.StructureToPtr for those. * common: Make MemoryHelper Read & Write takes unamanged types * Update Marshal.SizeOf => Unsafe.SizeOf when appropriate and start moving software applet to unmanaged types --- .../Extensions/BinaryReaderExtensions.cs | 43 +++------------------- 1 file changed, 5 insertions(+), 38 deletions(-) (limited to 'Ryujinx.Common/Extensions/BinaryReaderExtensions.cs') diff --git a/Ryujinx.Common/Extensions/BinaryReaderExtensions.cs b/Ryujinx.Common/Extensions/BinaryReaderExtensions.cs index 2c24678d..ea404d2a 100644 --- a/Ryujinx.Common/Extensions/BinaryReaderExtensions.cs +++ b/Ryujinx.Common/Extensions/BinaryReaderExtensions.cs @@ -1,5 +1,6 @@ using System; using System.IO; +using System.Runtime.CompilerServices; using System.Runtime.InteropServices; namespace Ryujinx.Common @@ -7,49 +8,15 @@ namespace Ryujinx.Common public static class BinaryReaderExtensions { public unsafe static T ReadStruct(this BinaryReader reader) - where T : struct + where T : unmanaged { - int size = Marshal.SizeOf(); - - byte[] data = reader.ReadBytes(size); - - fixed (byte* ptr = data) - { - return Marshal.PtrToStructure((IntPtr)ptr); - } - } - - public unsafe static T[] ReadStructArray(this BinaryReader reader, int count) - where T : struct - { - int size = Marshal.SizeOf(); - - T[] result = new T[count]; - - for (int i = 0; i < count; i++) - { - byte[] data = reader.ReadBytes(size); - - fixed (byte* ptr = data) - { - result[i] = Marshal.PtrToStructure((IntPtr)ptr); - } - } - - return result; + return MemoryMarshal.Cast(reader.ReadBytes(Unsafe.SizeOf()))[0]; } public unsafe static void WriteStruct(this BinaryWriter writer, T value) - where T : struct + where T : unmanaged { - long size = Marshal.SizeOf(); - - byte[] data = new byte[size]; - - fixed (byte* ptr = data) - { - Marshal.StructureToPtr(value, (IntPtr)ptr, false); - } + ReadOnlySpan data = MemoryMarshal.Cast(MemoryMarshal.CreateReadOnlySpan(ref value, 1)); writer.Write(data); } -- cgit v1.2.3