feat: add SafeMemory.PtrToStructure/<T>

This commit is contained in:
goat 2021-12-07 22:05:01 +01:00
parent 65d0acaf64
commit ca15a9c035
No known key found for this signature in database
GPG key ID: 7773BB5B43BA52E5
2 changed files with 27 additions and 10 deletions

View file

@ -190,6 +190,21 @@ namespace Dalamud
return WriteBytes(address, encoding.GetBytes(str + "\0"));
}
public static T? PtrToStructure<T>(IntPtr addr) where T : struct => (T?)PtrToStructure(addr, typeof(T));
public static object? PtrToStructure(IntPtr addr, Type type)
{
var size = Marshal.SizeOf(type);
if (!ReadBytes(addr, size, out var buffer))
return null;
var mem = new LocalMemory(size);
mem.Write(buffer);
return mem.Read(type);
}
/// <summary>
/// Get the size of the passed type.
/// </summary>
@ -249,6 +264,8 @@ namespace Dalamud
public T Read<T>(int offset = 0) => (T)Marshal.PtrToStructure(this.hGlobal + offset, typeof(T));
public object? Read(Type type, int offset = 0) => Marshal.PtrToStructure(this.hGlobal + offset, type);
public void Write(byte[] data, int index = 0) => Marshal.Copy(data, index, this.hGlobal, this.size);
public void Write<T>(T data, int offset = 0) => Marshal.StructureToPtr(data, this.hGlobal + offset, false);