Tanoda
StructMarshal.cs
Go to the documentation of this file.
1/******************************************************************************
2 * Copyright (C) Ultraleap, Inc. 2011-2020. *
3 * *
4 * Use subject to the terms of the Apache License 2.0 available at *
5 * http://www.apache.org/licenses/LICENSE-2.0, or another agreement *
6 * between Ultraleap and you, your company or other organization. *
7 ******************************************************************************/
8
9using System;
10using System.Runtime.InteropServices;
11
12namespace LeapInternal {
13
17 public static class StructMarshal<T> where T : struct {
18#if !ENABLE_IL2CPP
19 [StructLayout(LayoutKind.Sequential)]
20 private class StructContainer {
21 public T value;
22 }
23
24 [ThreadStatic]
25 private static StructContainer _container;
26#endif
27
28 private static int _sizeofT;
29
30 static StructMarshal() {
31 _sizeofT = Marshal.SizeOf(typeof(T));
32 }
33
38 public static int Size {
39 get {
40 return _sizeofT;
41 }
42 }
43
47 public static void PtrToStruct(IntPtr ptr, out T t) {
48#if ENABLE_IL2CPP
49#if UNITY_2018_1_OR_NEWER
50 unsafe {
51 Unity.Collections.LowLevel.Unsafe.UnsafeUtility.CopyPtrToStructure((void*)ptr, out t);
52 }
53#else
54#error UnityModules Only supports IL2CPP on versions of Unity 2018.1 or greater.
55#endif
56#else
57 if (_container == null) {
58 _container = new StructContainer();
59 }
60
61 try {
62 Marshal.PtrToStructure(ptr, _container);
63 t = _container.value;
64 } catch (Exception e) {
65 UnityEngine.Debug.LogException(e);
66 t = default(T);
67 }
68#endif
69 }
70
76 public static void ArrayElementToStruct(IntPtr ptr, int arrayIndex, out T t) {
77 PtrToStruct(new IntPtr(ptr.ToInt64() + _sizeofT * arrayIndex), out t);
78 }
79 }
80}