Welcome to mirror list, hosted at ThFree Co, Russian Federation.

SpanMarshallers.cs « Ancillary.Interop « tests « System.Runtime.InteropServices « libraries « src - github.com/dotnet/runtime.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 46cd7302fbff53cc1384cf4a4fe99b66b6bf20ca (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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.Diagnostics;
using System.Runtime.CompilerServices;

namespace System.Runtime.InteropServices.GeneratedMarshalling
{
    [GenericContiguousCollectionMarshaller]
    public unsafe ref struct ReadOnlySpanMarshaller<T>
    {
        private ReadOnlySpan<T> _managedSpan;
        private readonly int _sizeOfNativeElement;
        private IntPtr _allocatedMemory;

        public ReadOnlySpanMarshaller(int sizeOfNativeElement)
            : this()
        {
            _sizeOfNativeElement = sizeOfNativeElement;
        }

        public ReadOnlySpanMarshaller(ReadOnlySpan<T> managed, int sizeOfNativeElement)
            :this(managed, Span<byte>.Empty, sizeOfNativeElement)
        {
        }

        public ReadOnlySpanMarshaller(ReadOnlySpan<T> managed, Span<byte> stackSpace, int sizeOfNativeElement)
        {
            _allocatedMemory = default;
            _sizeOfNativeElement = sizeOfNativeElement;
            if (managed.Length == 0)
            {
                _managedSpan = default;
                NativeValueStorage = default;
                return;
            }
            _managedSpan = managed;
            int spaceToAllocate = managed.Length * sizeOfNativeElement;
            if (spaceToAllocate <= stackSpace.Length)
            {
                NativeValueStorage = stackSpace[0..spaceToAllocate];
            }
            else
            {
                _allocatedMemory = Marshal.AllocCoTaskMem(spaceToAllocate);
                NativeValueStorage = new Span<byte>((void*)_allocatedMemory, spaceToAllocate);
            }
        }

        /// <summary>
        /// Stack-alloc threshold set to 256 bytes to enable small arrays to be passed on the stack.
        /// Number kept small to ensure that P/Invokes with a lot of array parameters doesn't
        /// blow the stack since this is a new optimization in the code-generated interop.
        /// </summary>
        public const int BufferSize = 0x200;
        public const bool RequiresStackBuffer = true;

        public Span<T> ManagedValues => MemoryMarshal.CreateSpan(ref MemoryMarshal.GetReference(_managedSpan), _managedSpan.Length);

        public Span<byte> NativeValueStorage { get; private set; }

        public ref byte GetPinnableReference() => ref MemoryMarshal.GetReference(NativeValueStorage);

        public void SetUnmarshalledCollectionLength(int length)
        {
            _managedSpan = new T[length];
        }

        public byte* Value
        {
            get
            {
                return (byte*)Unsafe.AsPointer(ref GetPinnableReference());
            }
            set
            {
                if (value == null)
                {
                    _managedSpan = null;
                    NativeValueStorage = default;
                }
                else
                {
                    _allocatedMemory = (IntPtr)value;
                    NativeValueStorage = new Span<byte>(value, _managedSpan.Length * _sizeOfNativeElement);
                }
            }
        }

        public ReadOnlySpan<T> ToManaged() => _managedSpan;

        public void FreeNative()
        {
            Marshal.FreeCoTaskMem(_allocatedMemory);
        }
    }

    [GenericContiguousCollectionMarshaller]
    public unsafe ref struct SpanMarshaller<T>
    {
        private ReadOnlySpanMarshaller<T> _inner;

        public SpanMarshaller(int sizeOfNativeElement)
            : this()
        {
            _inner = new ReadOnlySpanMarshaller<T>(sizeOfNativeElement);
        }

        public SpanMarshaller(Span<T> managed, int sizeOfNativeElement)
        {
            _inner = new ReadOnlySpanMarshaller<T>(managed, sizeOfNativeElement);
        }

        public SpanMarshaller(Span<T> managed, Span<byte> stackSpace, int sizeOfNativeElement)
        {
            _inner = new ReadOnlySpanMarshaller<T>(managed, stackSpace, sizeOfNativeElement);
        }

        /// <summary>
        /// Stack-alloc threshold set to 256 bytes to enable small arrays to be passed on the stack.
        /// Number kept small to ensure that P/Invokes with a lot of array parameters doesn't
        /// blow the stack since this is a new optimization in the code-generated interop.
        /// </summary>
        public const int BufferSize = ReadOnlySpanMarshaller<T>.BufferSize;
        public const bool RequiresStackBuffer = ReadOnlySpanMarshaller<T>.RequiresStackBuffer;

        public Span<T> ManagedValues => _inner.ManagedValues;

        public Span<byte> NativeValueStorage
        {
            get => _inner.NativeValueStorage;
        }

        public ref byte GetPinnableReference() => ref _inner.GetPinnableReference();

        public void SetUnmarshalledCollectionLength(int length)
        {
            _inner.SetUnmarshalledCollectionLength(length);
        }

        public byte* Value
        {
            get => _inner.Value;
            set => _inner.Value = value;
        }

        public Span<T> ToManaged()
        {
            ReadOnlySpan<T> managedInner = _inner.ToManaged();
            return MemoryMarshal.CreateSpan(ref MemoryMarshal.GetReference(managedInner), managedInner.Length);
        }

        public void FreeNative()
        {
            _inner.FreeNative();
        }
    }

    [GenericContiguousCollectionMarshaller]
    public unsafe ref struct NeverNullSpanMarshaller<T>
    {
        private SpanMarshaller<T> _inner;

        public NeverNullSpanMarshaller(int sizeOfNativeElement)
            : this()
        {
            _inner = new SpanMarshaller<T>(sizeOfNativeElement);
        }

        public NeverNullSpanMarshaller(Span<T> managed, int sizeOfNativeElement)
        {
            _inner = new SpanMarshaller<T>(managed, sizeOfNativeElement);
        }

        public NeverNullSpanMarshaller(Span<T> managed, Span<byte> stackSpace, int sizeOfNativeElement)
        {
            _inner = new SpanMarshaller<T>(managed, stackSpace, sizeOfNativeElement);
        }

        /// <summary>
        /// Stack-alloc threshold set to 256 bytes to enable small spans to be passed on the stack.
        /// Number kept small to ensure that P/Invokes with a lot of span parameters doesn't
        /// blow the stack.
        /// </summary>
        public const int BufferSize = SpanMarshaller<T>.BufferSize;

        public Span<T> ManagedValues => _inner.ManagedValues;

        public Span<byte> NativeValueStorage
        {
            get => _inner.NativeValueStorage;
        }

        public ref byte GetPinnableReference()
        {
            if (_inner.ManagedValues.Length == 0)
            {
                return ref *(byte*)0xa5a5a5a5;
            }
            return ref _inner.GetPinnableReference();
        }

        public void SetUnmarshalledCollectionLength(int length)
        {
            _inner.SetUnmarshalledCollectionLength(length);
        }

        public byte* Value
        {
            get
            {
                if (_inner.ManagedValues.Length == 0)
                {
                    return (byte*)0xa5a5a5a5;
                }
                return _inner.Value;
            }

            set => _inner.Value = value;
        }

        public Span<T> ToManaged() => _inner.ToManaged();

        public void FreeNative()
        {
            _inner.FreeNative();
        }
    }

    [GenericContiguousCollectionMarshaller]
    public unsafe ref struct NeverNullReadOnlySpanMarshaller<T>
    {
        private ReadOnlySpanMarshaller<T> _inner;

        public NeverNullReadOnlySpanMarshaller(int sizeOfNativeElement)
            : this()
        {
            _inner = new ReadOnlySpanMarshaller<T>(sizeOfNativeElement);
        }

        public NeverNullReadOnlySpanMarshaller(ReadOnlySpan<T> managed, int sizeOfNativeElement)
        {
            _inner = new ReadOnlySpanMarshaller<T>(managed, sizeOfNativeElement);
        }

        public NeverNullReadOnlySpanMarshaller(ReadOnlySpan<T> managed, Span<byte> stackSpace, int sizeOfNativeElement)
        {
            _inner = new ReadOnlySpanMarshaller<T>(managed, stackSpace, sizeOfNativeElement);
        }

        /// <summary>
        /// Stack-alloc threshold set to 256 bytes to enable small spans to be passed on the stack.
        /// Number kept small to ensure that P/Invokes with a lot of span parameters doesn't
        /// blow the stack.
        /// </summary>
        public const int BufferSize = SpanMarshaller<T>.BufferSize;
        public const bool RequiresStackBuffer = SpanMarshaller<T>.RequiresStackBuffer;

        public Span<T> ManagedValues => _inner.ManagedValues;

        public Span<byte> NativeValueStorage
        {
            get => _inner.NativeValueStorage;
        }

        public ref byte GetPinnableReference()
        {
            if (_inner.ManagedValues.Length == 0)
            {
                return ref *(byte*)0xa5a5a5a5;
            }
            return ref _inner.GetPinnableReference();
        }

        public void SetUnmarshalledCollectionLength(int length)
        {
            _inner.SetUnmarshalledCollectionLength(length);
        }

        public byte* Value
        {
            get
            {
                if (_inner.ManagedValues.Length == 0)
                {
                    return (byte*)0xa5a5a5a5;
                }
                return _inner.Value;
            }

            set => _inner.Value = value;
        }

        public ReadOnlySpan<T> ToManaged() => _inner.ToManaged();

        public void FreeNative()
        {
            _inner.FreeNative();
        }
    }

    [GenericContiguousCollectionMarshaller]
    public unsafe ref struct DirectSpanMarshaller<T>
        where T : unmanaged
    {
        private int _unmarshalledLength;
        private T* _allocatedMemory;
        private Span<T> _data;

        public DirectSpanMarshaller(int sizeOfNativeElement)
            :this()
        {
            // This check is not exhaustive, but it will catch the majority of cases.
            if (typeof(T) == typeof(bool) || typeof(T) == typeof(char) || Unsafe.SizeOf<T>() != sizeOfNativeElement)
            {
                throw new ArgumentException("This marshaller only supports blittable element types. The provided type parameter must be blittable", nameof(T));
            }
        }

        public DirectSpanMarshaller(Span<T> managed, int sizeOfNativeElement)
            :this(sizeOfNativeElement)
        {
            if (managed.Length == 0)
            {
                return;
            }

            int spaceToAllocate = managed.Length * Unsafe.SizeOf<T>();
            _allocatedMemory = (T*)Marshal.AllocCoTaskMem(spaceToAllocate);
            _data = managed;
        }

        public DirectSpanMarshaller(Span<T> managed, Span<byte> stackSpace, int sizeOfNativeElement)
            :this(sizeOfNativeElement)
        {
            Debug.Assert(stackSpace.IsEmpty);
            _data = managed;
        }

        /// <summary>
        /// Stack-alloc threshold set to 0 so that the generator can use the constructor that takes a stackSpace to let the marshaller know that the original data span can be used and safely pinned.
        /// </summary>
        public const int BufferSize = 0;

        public Span<T> ManagedValues => _data;

        public Span<byte> NativeValueStorage => _allocatedMemory != null
            ? new Span<byte>(_allocatedMemory, _data.Length * Unsafe.SizeOf<T>())
            : MemoryMarshal.Cast<T, byte>(_data);

        public ref T GetPinnableReference() => ref _data.GetPinnableReference();

        public void SetUnmarshalledCollectionLength(int length)
        {
            _unmarshalledLength = length;
        }

        public T* Value
        {
            get
            {
                if (_allocatedMemory  != null)
                {
                    return _allocatedMemory;
                }
                return (T*)Unsafe.AsPointer(ref GetPinnableReference());
            }
            set
            {
                // We don't save the pointer assigned here to be freed
                // since this marshaller passes back the actual memory span from native code
                // back to managed code.
                _allocatedMemory = null;
                _data = new Span<T>(value, _unmarshalledLength);
            }
        }

        public Span<T> ToManaged()
        {
            return _data;
        }

        public void FreeNative()
        {
            Marshal.FreeCoTaskMem((IntPtr)_allocatedMemory);
        }
    }
}