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
This commit is contained in:
parent
a1ddaa2736
commit
f4e879a1e6
16 changed files with 88 additions and 137 deletions
|
@ -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<T>(this BinaryReader reader)
|
||||
where T : struct
|
||||
where T : unmanaged
|
||||
{
|
||||
int size = Marshal.SizeOf<T>();
|
||||
|
||||
byte[] data = reader.ReadBytes(size);
|
||||
|
||||
fixed (byte* ptr = data)
|
||||
{
|
||||
return Marshal.PtrToStructure<T>((IntPtr)ptr);
|
||||
}
|
||||
}
|
||||
|
||||
public unsafe static T[] ReadStructArray<T>(this BinaryReader reader, int count)
|
||||
where T : struct
|
||||
{
|
||||
int size = Marshal.SizeOf<T>();
|
||||
|
||||
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<T>((IntPtr)ptr);
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
return MemoryMarshal.Cast<byte, T>(reader.ReadBytes(Unsafe.SizeOf<T>()))[0];
|
||||
}
|
||||
|
||||
public unsafe static void WriteStruct<T>(this BinaryWriter writer, T value)
|
||||
where T : struct
|
||||
where T : unmanaged
|
||||
{
|
||||
long size = Marshal.SizeOf<T>();
|
||||
|
||||
byte[] data = new byte[size];
|
||||
|
||||
fixed (byte* ptr = data)
|
||||
{
|
||||
Marshal.StructureToPtr<T>(value, (IntPtr)ptr, false);
|
||||
}
|
||||
ReadOnlySpan<byte> data = MemoryMarshal.Cast<T, byte>(MemoryMarshal.CreateReadOnlySpan(ref value, 1));
|
||||
|
||||
writer.Write(data);
|
||||
}
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue