forked from SharpGenTools/SharpGenTools
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCppObjectMultiShadow.cs
More file actions
81 lines (70 loc) · 2.13 KB
/
Copy pathCppObjectMultiShadow.cs
File metadata and controls
81 lines (70 loc) · 2.13 KB
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
#nullable enable
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;
namespace SharpGen.Runtime;
internal sealed class CppObjectMultiShadow
{
private readonly GCHandle[] _shadows;
public CppObjectMultiShadow(GCHandle[] shadows)
{
_shadows = shadows ?? throw new ArgumentNullException(nameof(shadows));
#if DEBUG
foreach (var handle in _shadows)
{
Debug.Assert(handle.IsAllocated);
Debug.Assert(handle.Target is CppObjectShadow or CppObjectMultiShadow);
}
#endif
}
public T? ToShadow<T>() where T : CppObjectShadow
{
foreach (var handle in _shadows)
{
switch (handle.Target)
{
case T shadow:
return shadow;
case CppObjectMultiShadow multiShadow when multiShadow.ToShadow<T>() is { } shadow:
return shadow;
}
}
return null;
}
public bool ToCallback<T>([NotNullWhen(true)] out T? value) where T : ICallbackable
{
foreach (var handle in _shadows)
{
switch (handle.Target)
{
case CppObjectShadow shadow:
value = shadow.ToCallback<T>();
return true;
case CppObjectMultiShadow multiShadow when multiShadow.ToShadow<CppObjectShadow>() is { } shadow:
value = shadow.ToCallback<T>();
return true;
}
}
value = default;
return false;
}
internal void AddShadowsToSet(HashSet<CppObjectShadow> shadows)
{
foreach (var handle in _shadows)
{
if (!handle.IsAllocated)
continue;
switch (handle.Target)
{
case CppObjectShadow shadow:
shadows.Add(shadow);
break;
case CppObjectMultiShadow multiShadow:
multiShadow.AddShadowsToSet(shadows);
break;
}
}
}
}