説明なし
選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

NativeReference.cs 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439
  1. using System;
  2. using System.Diagnostics;
  3. using System.Runtime.InteropServices;
  4. using Unity.Burst;
  5. using Unity.Collections.LowLevel.Unsafe;
  6. using Unity.Jobs;
  7. namespace Unity.Collections
  8. {
  9. /// <summary>
  10. /// An unmanaged single value.
  11. /// </summary>
  12. /// <remarks>The functional equivalent of an array of length 1.
  13. /// When you need just one value, NativeReference can be preferable to an array because it better conveys the intent.</remarks>
  14. /// <typeparam name="T">The type of value.</typeparam>
  15. [StructLayout(LayoutKind.Sequential)]
  16. [NativeContainer]
  17. [BurstCompatible(GenericTypeArguments = new [] { typeof(int) })]
  18. public unsafe struct NativeReference<T>
  19. : INativeDisposable
  20. , IEquatable<NativeReference<T>>
  21. where T : unmanaged
  22. {
  23. [NativeDisableUnsafePtrRestriction]
  24. internal void* m_Data;
  25. #if ENABLE_UNITY_COLLECTIONS_CHECKS
  26. internal AtomicSafetyHandle m_Safety;
  27. static readonly SharedStatic<int> s_SafetyId = SharedStatic<int>.GetOrCreate<NativeReference<T>>();
  28. #if REMOVE_DISPOSE_SENTINEL
  29. #else
  30. [NativeSetClassTypeToNullOnSchedule]
  31. DisposeSentinel m_DisposeSentinel;
  32. #endif
  33. #endif
  34. internal AllocatorManager.AllocatorHandle m_AllocatorLabel;
  35. /// <summary>
  36. /// Initializes and returns an instance of NativeReference.
  37. /// </summary>
  38. /// <param name="allocator">The allocator to use.</param>
  39. /// <param name="options">Whether newly allocated bytes should be zeroed out.</param>
  40. public NativeReference(AllocatorManager.AllocatorHandle allocator, NativeArrayOptions options = NativeArrayOptions.ClearMemory)
  41. {
  42. Allocate(allocator, out this);
  43. if (options == NativeArrayOptions.ClearMemory)
  44. {
  45. UnsafeUtility.MemClear(m_Data, UnsafeUtility.SizeOf<T>());
  46. }
  47. }
  48. /// <summary>
  49. /// Initializes and returns an instance of NativeReference.
  50. /// </summary>
  51. /// <param name="allocator">The allocator to use.</param>
  52. /// <param name="value">The initial value.</param>
  53. public NativeReference(T value, AllocatorManager.AllocatorHandle allocator)
  54. {
  55. Allocate(allocator, out this);
  56. *(T*)m_Data = value;
  57. }
  58. static void Allocate(AllocatorManager.AllocatorHandle allocator, out NativeReference<T> reference)
  59. {
  60. CollectionHelper.CheckAllocator(allocator);
  61. reference = default;
  62. reference.m_Data = Memory.Unmanaged.Allocate(UnsafeUtility.SizeOf<T>(), UnsafeUtility.AlignOf<T>(), allocator);
  63. reference.m_AllocatorLabel = allocator;
  64. #if ENABLE_UNITY_COLLECTIONS_CHECKS
  65. #if REMOVE_DISPOSE_SENTINEL
  66. reference.m_Safety = CollectionHelper.CreateSafetyHandle(allocator);
  67. #else
  68. if (allocator.IsCustomAllocator)
  69. {
  70. reference.m_Safety = AtomicSafetyHandle.Create();
  71. reference.m_DisposeSentinel = null;
  72. }
  73. else
  74. {
  75. DisposeSentinel.Create(out reference.m_Safety, out reference.m_DisposeSentinel, 1, allocator.ToAllocator);
  76. }
  77. #endif
  78. CollectionHelper.SetStaticSafetyId<NativeQueue<T>>(ref reference.m_Safety, ref s_SafetyId.Data);
  79. #endif
  80. }
  81. /// <summary>
  82. /// The value stored in this reference.
  83. /// </summary>
  84. /// <param name="value">The new value to store in this reference.</param>
  85. /// <value>The value stored in this reference.</value>
  86. public T Value
  87. {
  88. get
  89. {
  90. #if ENABLE_UNITY_COLLECTIONS_CHECKS
  91. AtomicSafetyHandle.CheckReadAndThrow(m_Safety);
  92. #endif
  93. return *(T*)m_Data;
  94. }
  95. set
  96. {
  97. #if ENABLE_UNITY_COLLECTIONS_CHECKS
  98. AtomicSafetyHandle.CheckWriteAndThrow(m_Safety);
  99. #endif
  100. *(T*)m_Data = value;
  101. }
  102. }
  103. /// <summary>
  104. /// Whether this reference has been allocated (and not yet deallocated).
  105. /// </summary>
  106. /// <value>True if this reference has been allocated (and not yet deallocated).</value>
  107. public bool IsCreated => m_Data != null;
  108. /// <summary>
  109. /// Releases all resources (memory and safety handles).
  110. /// </summary>
  111. public void Dispose()
  112. {
  113. CheckNotDisposed();
  114. if (CollectionHelper.ShouldDeallocate(m_AllocatorLabel))
  115. {
  116. #if ENABLE_UNITY_COLLECTIONS_CHECKS
  117. #if REMOVE_DISPOSE_SENTINEL
  118. CollectionHelper.DisposeSafetyHandle(ref m_Safety);
  119. #else
  120. DisposeSentinel.Dispose(ref m_Safety, ref m_DisposeSentinel);
  121. #endif
  122. #endif
  123. Memory.Unmanaged.Free(m_Data, m_AllocatorLabel);
  124. m_AllocatorLabel = Allocator.Invalid;
  125. }
  126. m_Data = null;
  127. }
  128. /// <summary>
  129. /// Creates and schedules a job that will release all resources (memory and safety handles) of this reference.
  130. /// </summary>
  131. /// <param name="inputDeps">A job handle. The newly scheduled job will depend upon this handle.</param>
  132. /// <returns>The handle of a new job that will release all resources (memory and safety handles) of this reference.</returns>
  133. [NotBurstCompatible /* This is not burst compatible because of IJob's use of a static IntPtr. Should switch to IJobBurstSchedulable in the future */]
  134. public JobHandle Dispose(JobHandle inputDeps)
  135. {
  136. CheckNotDisposed();
  137. if (CollectionHelper.ShouldDeallocate(m_AllocatorLabel))
  138. {
  139. #if ENABLE_UNITY_COLLECTIONS_CHECKS
  140. #if REMOVE_DISPOSE_SENTINEL
  141. #else
  142. // [DeallocateOnJobCompletion] is not supported, but we want the deallocation
  143. // to happen in a thread. DisposeSentinel needs to be cleared on main thread.
  144. // AtomicSafetyHandle can be destroyed after the job was scheduled (Job scheduling
  145. // will check that no jobs are writing to the container).
  146. DisposeSentinel.Clear(ref m_DisposeSentinel);
  147. #endif
  148. #endif
  149. var jobHandle = new NativeReferenceDisposeJob
  150. {
  151. Data = new NativeReferenceDispose
  152. {
  153. m_Data = m_Data,
  154. m_AllocatorLabel = m_AllocatorLabel,
  155. #if ENABLE_UNITY_COLLECTIONS_CHECKS
  156. m_Safety = m_Safety
  157. #endif
  158. }
  159. }.Schedule(inputDeps);
  160. #if ENABLE_UNITY_COLLECTIONS_CHECKS
  161. AtomicSafetyHandle.Release(m_Safety);
  162. #endif
  163. m_Data = null;
  164. m_AllocatorLabel = Allocator.Invalid;
  165. return jobHandle;
  166. }
  167. m_Data = null;
  168. return inputDeps;
  169. }
  170. /// <summary>
  171. /// Copy the value of another reference to this reference.
  172. /// </summary>
  173. /// <param name="reference">The reference to copy from.</param>
  174. public void CopyFrom(NativeReference<T> reference)
  175. {
  176. Copy(this, reference);
  177. }
  178. /// <summary>
  179. /// Copy the value of this reference to another reference.
  180. /// </summary>
  181. /// <param name="reference">The reference to copy to.</param>
  182. public void CopyTo(NativeReference<T> reference)
  183. {
  184. Copy(reference, this);
  185. }
  186. /// <summary>
  187. /// Returns true if the value stored in this reference is equal to the value stored in another reference.
  188. /// </summary>
  189. /// <param name="other">A reference to compare with.</param>
  190. /// <returns>True if the value stored in this reference is equal to the value stored in another reference.</returns>
  191. [NotBurstCompatible]
  192. public bool Equals(NativeReference<T> other)
  193. {
  194. return Value.Equals(other.Value);
  195. }
  196. /// <summary>
  197. /// Returns true if the value stored in this reference is equal to an object.
  198. /// </summary>
  199. /// <remarks>Can only be equal if the object is itself a NativeReference.</remarks>
  200. /// <param name="obj">An object to compare with.</param>
  201. /// <returns>True if the value stored in this reference is equal to the object.</returns>
  202. [NotBurstCompatible]
  203. public override bool Equals(object obj)
  204. {
  205. if (ReferenceEquals(null, obj))
  206. {
  207. return false;
  208. }
  209. return obj is NativeReference<T> && Equals((NativeReference<T>)obj);
  210. }
  211. /// <summary>
  212. /// Returns the hash code of this reference.
  213. /// </summary>
  214. /// <returns>The hash code of this reference.</returns>
  215. public override int GetHashCode()
  216. {
  217. return Value.GetHashCode();
  218. }
  219. /// <summary>
  220. /// Returns true if the values stored in two references are equal.
  221. /// </summary>
  222. /// <param name="left">A reference.</param>
  223. /// <param name="right">Another reference.</param>
  224. /// <returns>True if the two values are equal.</returns>
  225. public static bool operator ==(NativeReference<T> left, NativeReference<T> right)
  226. {
  227. return left.Equals(right);
  228. }
  229. /// <summary>
  230. /// Returns true if the values stored in two references are unequal.
  231. /// </summary>
  232. /// <param name="left">A reference.</param>
  233. /// <param name="right">Another reference.</param>
  234. /// <returns>True if the two values are unequal.</returns>
  235. public static bool operator !=(NativeReference<T> left, NativeReference<T> right)
  236. {
  237. return !left.Equals(right);
  238. }
  239. /// <summary>
  240. /// Copies the value of a reference to another reference.
  241. /// </summary>
  242. /// <param name="dst">The destination reference.</param>
  243. /// <param name="src">The source reference.</param>
  244. public static void Copy(NativeReference<T> dst, NativeReference<T> src)
  245. {
  246. #if ENABLE_UNITY_COLLECTIONS_CHECKS
  247. AtomicSafetyHandle.CheckReadAndThrow(src.m_Safety);
  248. AtomicSafetyHandle.CheckWriteAndThrow(dst.m_Safety);
  249. #endif
  250. UnsafeUtility.MemCpy(dst.m_Data, src.m_Data, UnsafeUtility.SizeOf<T>());
  251. }
  252. /// <summary>
  253. /// Returns a read-only reference aliasing the value of this reference.
  254. /// </summary>
  255. /// <returns>A read-only reference aliasing the value of this reference.</returns>
  256. public ReadOnly AsReadOnly()
  257. {
  258. #if ENABLE_UNITY_COLLECTIONS_CHECKS
  259. return new ReadOnly(m_Data, ref m_Safety);
  260. #else
  261. return new ReadOnly(m_Data);
  262. #endif
  263. }
  264. /// <summary>
  265. /// A read-only alias for the value of a NativeReference. Does not have its own allocated storage.
  266. /// </summary>
  267. [NativeContainer]
  268. [NativeContainerIsReadOnly]
  269. [BurstCompatible(GenericTypeArguments = new [] { typeof(int) })]
  270. public unsafe struct ReadOnly
  271. {
  272. [NativeDisableUnsafePtrRestriction]
  273. readonly void* m_Data;
  274. #if ENABLE_UNITY_COLLECTIONS_CHECKS
  275. AtomicSafetyHandle m_Safety;
  276. internal static readonly SharedStatic<int> s_staticSafetyId = SharedStatic<int>.GetOrCreate<ReadOnly>();
  277. [BurstCompatible(CompileTarget = BurstCompatibleAttribute.BurstCompatibleCompileTarget.Editor)]
  278. internal ReadOnly(void* data, ref AtomicSafetyHandle safety)
  279. {
  280. m_Data = data;
  281. m_Safety = safety;
  282. CollectionHelper.SetStaticSafetyId<ReadOnly>(ref m_Safety, ref s_staticSafetyId.Data);
  283. }
  284. #else
  285. internal ReadOnly(void* data)
  286. {
  287. m_Data = data;
  288. }
  289. #endif
  290. /// <summary>
  291. /// The value aliased by this reference.
  292. /// </summary>
  293. /// <value>The value aliased by the reference.</value>
  294. public T Value
  295. {
  296. get
  297. {
  298. #if ENABLE_UNITY_COLLECTIONS_CHECKS
  299. AtomicSafetyHandle.CheckReadAndThrow(m_Safety);
  300. #endif
  301. return *(T*)m_Data;
  302. }
  303. }
  304. }
  305. [Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS")]
  306. void CheckNotDisposed()
  307. {
  308. if (m_Data == null)
  309. throw new ObjectDisposedException("The NativeReference is already disposed.");
  310. }
  311. }
  312. [NativeContainer]
  313. unsafe struct NativeReferenceDispose
  314. {
  315. [NativeDisableUnsafePtrRestriction]
  316. internal void* m_Data;
  317. internal AllocatorManager.AllocatorHandle m_AllocatorLabel;
  318. #if ENABLE_UNITY_COLLECTIONS_CHECKS
  319. internal AtomicSafetyHandle m_Safety;
  320. #endif
  321. public void Dispose()
  322. {
  323. Memory.Unmanaged.Free(m_Data, m_AllocatorLabel);
  324. }
  325. }
  326. [BurstCompile]
  327. struct NativeReferenceDisposeJob : IJob
  328. {
  329. internal NativeReferenceDispose Data;
  330. public void Execute()
  331. {
  332. Data.Dispose();
  333. }
  334. }
  335. }
  336. namespace Unity.Collections.LowLevel.Unsafe
  337. {
  338. /// <summary>
  339. /// Provides extension methods for NativeReference.
  340. /// </summary>
  341. [BurstCompatible]
  342. public static class NativeReferenceUnsafeUtility
  343. {
  344. /// <summary>
  345. /// Returns a pointer to this reference's stored value.
  346. /// </summary>
  347. /// <remarks>Performs a job safety check for read-write access.</remarks>
  348. /// <typeparam name="T">The type of the value.</typeparam>
  349. /// <param name="reference">The reference.</param>
  350. /// <returns>A pointer to this reference's stored value.</returns>
  351. [BurstCompatible(GenericTypeArguments = new [] { typeof(int) })]
  352. public static unsafe void* GetUnsafePtr<T>(this NativeReference<T> reference)
  353. where T : unmanaged
  354. {
  355. #if ENABLE_UNITY_COLLECTIONS_CHECKS
  356. AtomicSafetyHandle.CheckWriteAndThrow(reference.m_Safety);
  357. #endif
  358. return reference.m_Data;
  359. }
  360. /// <summary>
  361. /// Returns a pointer to this reference's stored value.
  362. /// </summary>
  363. /// <remarks>Performs a job safety check for read-only access.</remarks>
  364. /// <typeparam name="T">The type of the value.</typeparam>
  365. /// <param name="reference">The reference.</param>
  366. /// <returns>A pointer to this reference's stored value.</returns>
  367. [BurstCompatible(GenericTypeArguments = new [] { typeof(int) })]
  368. public static unsafe void* GetUnsafeReadOnlyPtr<T>(this NativeReference<T> reference)
  369. where T : unmanaged
  370. {
  371. #if ENABLE_UNITY_COLLECTIONS_CHECKS
  372. AtomicSafetyHandle.CheckReadAndThrow(reference.m_Safety);
  373. #endif
  374. return reference.m_Data;
  375. }
  376. /// <summary>
  377. /// Returns a pointer to this reference's stored value.
  378. /// </summary>
  379. /// <remarks>Performs no job safety checks.</remarks>
  380. /// <typeparam name="T">The type of the value.</typeparam>
  381. /// <param name="reference">The reference.</param>
  382. /// <returns>A pointer to this reference's stored value.</returns>
  383. [BurstCompatible(GenericTypeArguments = new [] { typeof(int) })]
  384. public static unsafe void* GetUnsafePtrWithoutChecks<T>(this NativeReference<T> reference)
  385. where T : unmanaged
  386. {
  387. return reference.m_Data;
  388. }
  389. }
  390. }