A game about forced loneliness, made by TACStudios
1using System;
2using System.Diagnostics;
3using System.Runtime.InteropServices;
4using Unity.Collections.LowLevel.Unsafe;
5
6namespace Unity.Burst
7{
8 /// <summary>
9 /// Base interface for a function pointer.
10 /// </summary>
11 public interface IFunctionPointer
12 {
13 /// <summary>
14 /// Converts a pointer to a function pointer.
15 /// </summary>
16 /// <param name="ptr">The native pointer.</param>
17 /// <returns>An instance of this interface.</returns>
18 [Obsolete("This method will be removed in a future version of Burst")]
19 IFunctionPointer FromIntPtr(IntPtr ptr);
20 }
21
22 /// <summary>
23 /// A function pointer that can be used from a Burst Job or from regular C#.
24 /// It needs to be compiled through <see cref="BurstCompiler.CompileFunctionPointer{T}"/>
25 /// </summary>
26 /// <typeparam name="T">Type of the delegate of this function pointer</typeparam>
27 public readonly struct FunctionPointer<T> : IFunctionPointer
28 {
29 // DOTSPLAYER's shim package relies on Burst for it's jobs code
30 // so Burst does not see the DOTSPLAYER definition of this attribute
31 [NativeDisableUnsafePtrRestriction]
32 private readonly IntPtr _ptr;
33
34 /// <summary>
35 /// Creates a new instance of this function pointer with the following native pointer.
36 /// </summary>
37 /// <param name="ptr">Native Pointer</param>
38 public FunctionPointer(IntPtr ptr)
39 {
40 _ptr = ptr;
41 }
42
43 /// <summary>
44 /// Gets the underlying pointer.
45 /// </summary>
46 public IntPtr Value => _ptr;
47
48 [Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS")]
49 private void CheckIsCreated()
50 {
51 if (!IsCreated)
52 {
53 throw new NullReferenceException("Object reference not set to an instance of an object");
54 }
55 }
56
57 /// <summary>
58 /// Gets the delegate associated to this function pointer in order to call the function pointer.
59 /// This delegate can be called from a Burst Job or from regular C#.
60 /// If calling from regular C#, it is recommended to cache the returned delegate of this property
61 /// instead of using this property every time you need to call the delegate.
62 /// </summary>
63 public T Invoke
64 {
65 get
66 {
67 CheckIsCreated();
68 return Marshal.GetDelegateForFunctionPointer<T>(_ptr);
69 }
70 }
71
72 /// <summary>
73 /// Whether the function pointer is valid.
74 /// </summary>
75 public bool IsCreated => _ptr != IntPtr.Zero;
76
77 /// <summary>
78 /// Converts a pointer to a function pointer.
79 /// </summary>
80 /// <param name="ptr">The native pointer.</param>
81 /// <returns>An instance of this interface.</returns>
82 IFunctionPointer IFunctionPointer.FromIntPtr(IntPtr ptr) => new FunctionPointer<T>(ptr);
83 }
84}