-
Notifications
You must be signed in to change notification settings - Fork 3
/
ManagedRef.cs
44 lines (37 loc) · 1.41 KB
/
ManagedRef.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
using System;
using System.Runtime.InteropServices;
namespace Arenas {
[StructLayout(LayoutKind.Sequential)]
public readonly struct ManagedRef {
private readonly IntPtr handle;
public ManagedRef(IntPtr handle) {
this.handle = handle;
}
public ManagedRef Set<T>(Arena arena, T value) where T : class {
if (arena is null) {
throw new NullReferenceException("Arena cannot be null in ManagedRef.Set");
}
return new ManagedRef(arena.SetOutsidePtr(value, handle));
}
public ManagedRef Set<TSource, TVal>(ref TSource source, TVal value) where TSource : unmanaged, IArenaContents where TVal : class {
var arena = Arena.Get(source.ArenaID);
if (arena is null) {
throw new NullReferenceException("Arena cannot be null in ManagedRef.Set");
}
return new ManagedRef(arena.SetOutsidePtr(value, handle));
}
public T Get<T>() where T : class {
if (handle == IntPtr.Zero) {
return null;
}
GCHandle gcHandle = GCHandle.FromIntPtr(handle);
return (T)gcHandle.Target;
}
public override string ToString() {
return $"ManagedRef(0x{handle:x})";
}
public static explicit operator IntPtr(ManagedRef ptr) {
return ptr.handle;
}
}
}