aboutsummaryrefslogtreecommitdiffstatsci
path: root/vulkan/PNext.cs
blob: 9ca9709e92308ea1f9b68337ccc4766f3633acdc (plain)
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
// This code is licensed under the MIT license (MIT) (http://opensource.org/licenses/MIT)
//
// Copyright (c) 2022 JP Bruyère
using System;
using System.Linq;
using System.Runtime.InteropServices;

namespace Vulkan
{
    /// <summary>
    /// Helper class to construct pnext chain
    /// </summary>
	public class PNext<T> : IDisposable where T : struct
	{
		IntPtr handle;
		/// <summary>
		/// Allocate on HGlobal a new structure of type T, ensure instance is Disposed.
		/// </summary>
		public PNext () {
			init();
		}
		/// <summary>
		/// Allocate on HGlobal a new structure of type T and set the pNext field,
		/// ensure instance is Disposed.
		/// </summary>
		public PNext (IntPtr pNext) {
			init();
			Marshal.WriteIntPtr(handle + 4, pNext);
		}
		/// <summary>
		/// Allocate on HGlobal a new structure of type T and set current value
		/// ensure instance is Disposed.
		/// </summary>
		public PNext (T instance) {
			handle = Marshal.AllocHGlobal(Marshal.SizeOf<T>());
			Marshal.StructureToPtr(instance, handle, false);
		}
		/// <summary>
		/// Allocate on HGlobal a new structure of type T set current value and
		/// the PNext field.
		/// ensure instance is Disposed.
		/// </summary>
		public PNext (T instance, IntPtr pNext) {
			handle = Marshal.AllocHGlobal(Marshal.SizeOf<T>());
			Marshal.StructureToPtr(instance, handle, false);
			Marshal.WriteIntPtr(handle + 4, pNext);
		}
		void init() {
			handle = Marshal.AllocHGlobal(Marshal.SizeOf<T>());
			Type t = typeof(T);
			StructureTypeAttribute st = (StructureTypeAttribute)t.GetCustomAttributes(typeof(StructureTypeAttribute), false).FirstOrDefault();
			Marshal.WriteInt32(handle, st.StructureType);
		}
		/// <summary>
		/// Get value of T
		/// </summary>
		public T Val => Marshal.PtrToStructure<T> (handle);
		public static implicit operator IntPtr(PNext<T> pn) => pn.handle;
		public void Dispose()
		{
			Marshal.FreeHGlobal(handle);
		}
	}
}