Skip to content

Commit 005a628

Browse files
committed
Use IL to achieve AOT visibility
1 parent 7b65313 commit 005a628

File tree

1 file changed

+13
-9
lines changed

1 file changed

+13
-9
lines changed

src/DotNext/Runtime/BoxedValue.cs

Lines changed: 13 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,10 @@
11
using System.Diagnostics;
22
using System.Diagnostics.CodeAnalysis;
33
using System.Runtime.CompilerServices;
4+
using static InlineIL.IL;
5+
using static InlineIL.IL.Emit;
6+
using static InlineIL.MethodRef;
7+
using static InlineIL.TypeRef;
48

59
namespace DotNext.Runtime;
610

@@ -25,13 +29,6 @@ namespace DotNext.Runtime;
2529
where T : struct
2630
{
2731
private T value;
28-
29-
static BoxedValue()
30-
{
31-
// AOT: instantiate the class to make instance members visible to AOT
32-
var boxed = new BoxedValue<T>();
33-
GC.KeepAlive(boxed);
34-
}
3532

3633
[ExcludeFromCodeCoverage]
3734
private BoxedValue()
@@ -66,15 +63,22 @@ private BoxedValue()
6663
/// </summary>
6764
/// <param name="value">The value to be boxed.</param>
6865
/// <returns>A boxed representation of the value.</returns>
69-
public static BoxedValue<T> Box(T value) => Unsafe.As<BoxedValue<T>>(value);
66+
public static BoxedValue<T> Box(T value)
67+
{
68+
Push(value);
69+
Box<T>();
70+
Dup();
71+
Call(Constructor(Type<BoxedValue<T>>()));
72+
return Return<BoxedValue<T>>();
73+
}
7074

7175
/// <summary>
7276
/// Boxes nullable value type to an object.
7377
/// </summary>
7478
/// <param name="value">The value to be boxed.</param>
7579
/// <returns>A boxed representation of the value.</returns>
7680
[return: NotNullIfNotNull(nameof(value))]
77-
public static BoxedValue<T>? TryBox(in T? value) => Unsafe.As<BoxedValue<T>?>(value);
81+
public static BoxedValue<T>? TryBox(in T? value) => value.HasValue ? Box(value.GetValueOrDefault()) : null;
7882

7983
/// <summary>
8084
/// Unboxes the value.

0 commit comments

Comments
 (0)