This repository has been archived by the owner on Nov 1, 2020. It is now read-only.
/
Marshal.cs
978 lines (818 loc) · 30 KB
/
Marshal.cs
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
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Security;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text;
using Internal.Runtime.CompilerServices;
using System.Diagnostics.CodeAnalysis;
#pragma warning disable SA1121 // explicitly using type aliases instead of built-in types
#if TARGET_64BIT
using nuint = System.UInt64;
#else
using nuint = System.UInt32;
#endif
namespace System.Runtime.InteropServices
{
/// <summary>
/// This class contains methods that are mainly used to marshal between unmanaged
/// and managed types.
/// </summary>
public static partial class Marshal
{
/// <summary>
/// The default character size for the system. This is always 2 because
/// the framework only runs on UTF-16 systems.
/// </summary>
public static readonly int SystemDefaultCharSize = 2;
/// <summary>
/// The max DBCS character size for the system.
/// </summary>
public static readonly int SystemMaxDBCSCharSize = GetSystemMaxDBCSCharSize();
public static IntPtr AllocHGlobal(int cb) => AllocHGlobal((IntPtr)cb);
public static unsafe string? PtrToStringAnsi(IntPtr ptr)
{
if (IsNullOrWin32Atom(ptr))
{
return null;
}
return new string((sbyte*)ptr);
}
public static unsafe string PtrToStringAnsi(IntPtr ptr, int len)
{
if (ptr == IntPtr.Zero)
{
throw new ArgumentNullException(nameof(ptr));
}
if (len < 0)
{
throw new ArgumentOutOfRangeException(nameof(len), len, SR.ArgumentOutOfRange_NeedNonNegNum);
}
return new string((sbyte*)ptr, 0, len);
}
public static unsafe string? PtrToStringUni(IntPtr ptr)
{
if (IsNullOrWin32Atom(ptr))
{
return null;
}
return new string((char*)ptr);
}
public static unsafe string PtrToStringUni(IntPtr ptr, int len)
{
if (ptr == IntPtr.Zero)
{
throw new ArgumentNullException(nameof(ptr));
}
if (len < 0)
{
throw new ArgumentOutOfRangeException(nameof(len), len, SR.ArgumentOutOfRange_NeedNonNegNum);
}
return new string((char*)ptr, 0, len);
}
public static unsafe string? PtrToStringUTF8(IntPtr ptr)
{
if (IsNullOrWin32Atom(ptr))
{
return null;
}
int nbBytes = string.strlen((byte*)ptr);
return string.CreateStringFromEncoding((byte*)ptr, nbBytes, Encoding.UTF8);
}
public static unsafe string PtrToStringUTF8(IntPtr ptr, int byteLen)
{
if (ptr == IntPtr.Zero)
{
throw new ArgumentNullException(nameof(ptr));
}
if (byteLen < 0)
{
throw new ArgumentOutOfRangeException(nameof(byteLen), byteLen, SR.ArgumentOutOfRange_NeedNonNegNum);
}
return string.CreateStringFromEncoding((byte*)ptr, byteLen, Encoding.UTF8);
}
public static int SizeOf(object structure)
{
if (structure is null)
{
throw new ArgumentNullException(nameof(structure));
}
return SizeOfHelper(structure.GetType(), throwIfNotMarshalable: true);
}
public static int SizeOf<T>(T structure)
{
if (structure is null)
{
throw new ArgumentNullException(nameof(structure));
}
return SizeOfHelper(structure.GetType(), throwIfNotMarshalable: true);
}
public static int SizeOf(Type t)
{
if (t is null)
{
throw new ArgumentNullException(nameof(t));
}
if (!t.IsRuntimeImplemented())
{
throw new ArgumentException(SR.Argument_MustBeRuntimeType, nameof(t));
}
if (t.IsGenericType)
{
throw new ArgumentException(SR.Argument_NeedNonGenericType, nameof(t));
}
return SizeOfHelper(t, throwIfNotMarshalable: true);
}
public static int SizeOf<T>() => SizeOf(typeof(T));
/// <summary>
/// IMPORTANT NOTICE: This method does not do any verification on the array.
/// It must be used with EXTREME CAUTION since passing in invalid index or
/// an array that is not pinned can cause unexpected results.
/// </summary>
public static unsafe IntPtr UnsafeAddrOfPinnedArrayElement(Array arr, int index)
{
if (arr is null)
throw new ArgumentNullException(nameof(arr));
void* pRawData = Unsafe.AsPointer(ref arr.GetRawArrayData());
return (IntPtr)((byte*)pRawData + (uint)index * (nuint)arr.GetElementSize());
}
public static unsafe IntPtr UnsafeAddrOfPinnedArrayElement<T>(T[] arr, int index)
{
if (arr is null)
throw new ArgumentNullException(nameof(arr));
void* pRawData = Unsafe.AsPointer(ref MemoryMarshal.GetArrayDataReference(arr));
return (IntPtr)((byte*)pRawData + (uint)index * (nuint)Unsafe.SizeOf<T>());
}
public static IntPtr OffsetOf<T>(string fieldName) => OffsetOf(typeof(T), fieldName);
public static void Copy(int[] source, int startIndex, IntPtr destination, int length)
{
CopyToNative(source, startIndex, destination, length);
}
public static void Copy(char[] source, int startIndex, IntPtr destination, int length)
{
CopyToNative(source, startIndex, destination, length);
}
public static void Copy(short[] source, int startIndex, IntPtr destination, int length)
{
CopyToNative(source, startIndex, destination, length);
}
public static void Copy(long[] source, int startIndex, IntPtr destination, int length)
{
CopyToNative(source, startIndex, destination, length);
}
public static void Copy(float[] source, int startIndex, IntPtr destination, int length)
{
CopyToNative(source, startIndex, destination, length);
}
public static void Copy(double[] source, int startIndex, IntPtr destination, int length)
{
CopyToNative(source, startIndex, destination, length);
}
public static void Copy(byte[] source, int startIndex, IntPtr destination, int length)
{
CopyToNative(source, startIndex, destination, length);
}
public static void Copy(IntPtr[] source, int startIndex, IntPtr destination, int length)
{
CopyToNative(source, startIndex, destination, length);
}
private static unsafe void CopyToNative<T>(T[] source, int startIndex, IntPtr destination, int length)
{
if (source is null)
throw new ArgumentNullException(nameof(source));
if (destination == IntPtr.Zero)
throw new ArgumentNullException(nameof(destination));
// The rest of the argument validation is done by CopyTo
new Span<T>(source, startIndex, length).CopyTo(new Span<T>((void*)destination, length));
}
public static void Copy(IntPtr source, int[] destination, int startIndex, int length)
{
CopyToManaged(source, destination, startIndex, length);
}
public static void Copy(IntPtr source, char[] destination, int startIndex, int length)
{
CopyToManaged(source, destination, startIndex, length);
}
public static void Copy(IntPtr source, short[] destination, int startIndex, int length)
{
CopyToManaged(source, destination, startIndex, length);
}
public static void Copy(IntPtr source, long[] destination, int startIndex, int length)
{
CopyToManaged(source, destination, startIndex, length);
}
public static void Copy(IntPtr source, float[] destination, int startIndex, int length)
{
CopyToManaged(source, destination, startIndex, length);
}
public static void Copy(IntPtr source, double[] destination, int startIndex, int length)
{
CopyToManaged(source, destination, startIndex, length);
}
public static void Copy(IntPtr source, byte[] destination, int startIndex, int length)
{
CopyToManaged(source, destination, startIndex, length);
}
public static void Copy(IntPtr source, IntPtr[] destination, int startIndex, int length)
{
CopyToManaged(source, destination, startIndex, length);
}
private static unsafe void CopyToManaged<T>(IntPtr source, T[] destination, int startIndex, int length)
{
if (source == IntPtr.Zero)
throw new ArgumentNullException(nameof(source));
if (destination is null)
throw new ArgumentNullException(nameof(destination));
if (startIndex < 0)
throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_StartIndex);
if (length < 0)
throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_NeedNonNegNum);
// The rest of the argument validation is done by CopyTo
new Span<T>((void*)source, length).CopyTo(new Span<T>(destination, startIndex, length));
}
public static unsafe byte ReadByte(IntPtr ptr, int ofs)
{
try
{
byte* addr = (byte*)ptr + ofs;
return *addr;
}
catch (NullReferenceException)
{
// this method is documented to throw AccessViolationException on any AV
throw new AccessViolationException();
}
}
public static byte ReadByte(IntPtr ptr) => ReadByte(ptr, 0);
public static unsafe short ReadInt16(IntPtr ptr, int ofs)
{
try
{
byte* addr = (byte*)ptr + ofs;
if ((unchecked((int)addr) & 0x1) == 0)
{
// aligned read
return *((short*)addr);
}
else
{
return Unsafe.ReadUnaligned<short>(addr);
}
}
catch (NullReferenceException)
{
// this method is documented to throw AccessViolationException on any AV
throw new AccessViolationException();
}
}
public static short ReadInt16(IntPtr ptr) => ReadInt16(ptr, 0);
public static unsafe int ReadInt32(IntPtr ptr, int ofs)
{
try
{
byte* addr = (byte*)ptr + ofs;
if ((unchecked((int)addr) & 0x3) == 0)
{
// aligned read
return *((int*)addr);
}
else
{
return Unsafe.ReadUnaligned<int>(addr);
}
}
catch (NullReferenceException)
{
// this method is documented to throw AccessViolationException on any AV
throw new AccessViolationException();
}
}
public static int ReadInt32(IntPtr ptr) => ReadInt32(ptr, 0);
public static IntPtr ReadIntPtr(object ptr, int ofs)
{
#if TARGET_64BIT
return (IntPtr)ReadInt64(ptr, ofs);
#else // 32
return (IntPtr)ReadInt32(ptr, ofs);
#endif
}
public static IntPtr ReadIntPtr(IntPtr ptr, int ofs)
{
#if TARGET_64BIT
return (IntPtr)ReadInt64(ptr, ofs);
#else // 32
return (IntPtr)ReadInt32(ptr, ofs);
#endif
}
public static IntPtr ReadIntPtr(IntPtr ptr) => ReadIntPtr(ptr, 0);
public static unsafe long ReadInt64(IntPtr ptr, int ofs)
{
try
{
byte* addr = (byte*)ptr + ofs;
if ((unchecked((int)addr) & 0x7) == 0)
{
// aligned read
return *((long*)addr);
}
else
{
return Unsafe.ReadUnaligned<long>(addr);
}
}
catch (NullReferenceException)
{
// this method is documented to throw AccessViolationException on any AV
throw new AccessViolationException();
}
}
public static long ReadInt64(IntPtr ptr) => ReadInt64(ptr, 0);
public static unsafe void WriteByte(IntPtr ptr, int ofs, byte val)
{
try
{
byte* addr = (byte*)ptr + ofs;
*addr = val;
}
catch (NullReferenceException)
{
// this method is documented to throw AccessViolationException on any AV
throw new AccessViolationException();
}
}
public static void WriteByte(IntPtr ptr, byte val) => WriteByte(ptr, 0, val);
public static unsafe void WriteInt16(IntPtr ptr, int ofs, short val)
{
try
{
byte* addr = (byte*)ptr + ofs;
if ((unchecked((int)addr) & 0x1) == 0)
{
// aligned write
*((short*)addr) = val;
}
else
{
Unsafe.WriteUnaligned(addr, val);
}
}
catch (NullReferenceException)
{
// this method is documented to throw AccessViolationException on any AV
throw new AccessViolationException();
}
}
public static void WriteInt16(IntPtr ptr, short val) => WriteInt16(ptr, 0, val);
public static void WriteInt16(IntPtr ptr, int ofs, char val) => WriteInt16(ptr, ofs, (short)val);
public static void WriteInt16([In, Out]object ptr, int ofs, char val) => WriteInt16(ptr, ofs, (short)val);
public static void WriteInt16(IntPtr ptr, char val) => WriteInt16(ptr, 0, (short)val);
public static unsafe void WriteInt32(IntPtr ptr, int ofs, int val)
{
try
{
byte* addr = (byte*)ptr + ofs;
if ((unchecked((int)addr) & 0x3) == 0)
{
// aligned write
*((int*)addr) = val;
}
else
{
Unsafe.WriteUnaligned(addr, val);
}
}
catch (NullReferenceException)
{
// this method is documented to throw AccessViolationException on any AV
throw new AccessViolationException();
}
}
public static void WriteInt32(IntPtr ptr, int val) => WriteInt32(ptr, 0, val);
public static void WriteIntPtr(IntPtr ptr, int ofs, IntPtr val)
{
#if TARGET_64BIT
WriteInt64(ptr, ofs, (long)val);
#else // 32
WriteInt32(ptr, ofs, (int)val);
#endif
}
public static void WriteIntPtr(object ptr, int ofs, IntPtr val)
{
#if TARGET_64BIT
WriteInt64(ptr, ofs, (long)val);
#else // 32
WriteInt32(ptr, ofs, (int)val);
#endif
}
public static void WriteIntPtr(IntPtr ptr, IntPtr val) => WriteIntPtr(ptr, 0, val);
public static unsafe void WriteInt64(IntPtr ptr, int ofs, long val)
{
try
{
byte* addr = (byte*)ptr + ofs;
if ((unchecked((int)addr) & 0x7) == 0)
{
// aligned write
*((long*)addr) = val;
}
else
{
Unsafe.WriteUnaligned(addr, val);
}
}
catch (NullReferenceException)
{
// this method is documented to throw AccessViolationException on any AV
throw new AccessViolationException();
}
}
public static void WriteInt64(IntPtr ptr, long val) => WriteInt64(ptr, 0, val);
public static void Prelink(MethodInfo m)
{
if (m is null)
{
throw new ArgumentNullException(nameof(m));
}
PrelinkCore(m);
}
public static void PrelinkAll(Type c)
{
if (c is null)
{
throw new ArgumentNullException(nameof(c));
}
MethodInfo[] mi = c.GetMethods();
for (int i = 0; i < mi.Length; i++)
{
Prelink(mi[i]);
}
}
public static void StructureToPtr<T>([DisallowNull] T structure, IntPtr ptr, bool fDeleteOld)
{
StructureToPtr((object)structure!, ptr, fDeleteOld);
}
/// <summary>
/// Creates a new instance of "structuretype" and marshals data from a
/// native memory block to it.
/// </summary>
public static object? PtrToStructure(IntPtr ptr, Type structureType)
{
if (ptr == IntPtr.Zero)
{
return null;
}
if (structureType is null)
{
throw new ArgumentNullException(nameof(structureType));
}
if (structureType.IsGenericType)
{
throw new ArgumentException(SR.Argument_NeedNonGenericType, nameof(structureType));
}
if (!structureType.IsRuntimeImplemented())
{
throw new ArgumentException(SR.Argument_MustBeRuntimeType, nameof(structureType));
}
return PtrToStructureHelper(ptr, structureType);
}
/// <summary>
/// Marshals data from a native memory block to a preallocated structure class.
/// </summary>
public static void PtrToStructure(IntPtr ptr, object structure)
{
PtrToStructureHelper(ptr, structure, allowValueClasses: false);
}
public static void PtrToStructure<T>(IntPtr ptr, [DisallowNull] T structure)
{
PtrToStructure(ptr, (object)structure!);
}
[return: MaybeNull]
public static T PtrToStructure<T>(IntPtr ptr) => (T)PtrToStructure(ptr, typeof(T))!;
public static void DestroyStructure<T>(IntPtr ptr) => DestroyStructure(ptr, typeof(T));
/// <summary>
/// Converts the HRESULT to a CLR exception.
/// </summary>
public static Exception? GetExceptionForHR(int errorCode) => GetExceptionForHR(errorCode, IntPtr.Zero);
public static Exception? GetExceptionForHR(int errorCode, IntPtr errorInfo)
{
if (errorCode >= 0)
{
return null;
}
return GetExceptionForHRInternal(errorCode, errorInfo);
}
/// <summary>
/// Throws a CLR exception based on the HRESULT.
/// </summary>
public static void ThrowExceptionForHR(int errorCode)
{
if (errorCode < 0)
{
throw GetExceptionForHR(errorCode, IntPtr.Zero)!;
}
}
public static void ThrowExceptionForHR(int errorCode, IntPtr errorInfo)
{
if (errorCode < 0)
{
throw GetExceptionForHR(errorCode, errorInfo)!;
}
}
public static IntPtr SecureStringToBSTR(SecureString s)
{
if (s is null)
{
throw new ArgumentNullException(nameof(s));
}
return s.MarshalToBSTR();
}
public static IntPtr SecureStringToCoTaskMemAnsi(SecureString s)
{
if (s is null)
{
throw new ArgumentNullException(nameof(s));
}
return s.MarshalToString(globalAlloc: false, unicode: false);
}
public static IntPtr SecureStringToCoTaskMemUnicode(SecureString s)
{
if (s is null)
{
throw new ArgumentNullException(nameof(s));
}
return s.MarshalToString(globalAlloc: false, unicode: true);
}
public static IntPtr SecureStringToGlobalAllocAnsi(SecureString s)
{
if (s is null)
{
throw new ArgumentNullException(nameof(s));
}
return s.MarshalToString(globalAlloc: true, unicode: false);
}
public static IntPtr SecureStringToGlobalAllocUnicode(SecureString s)
{
if (s is null)
{
throw new ArgumentNullException(nameof(s));
}
return s.MarshalToString(globalAlloc: true, unicode: true);
}
public static unsafe IntPtr StringToHGlobalAnsi(string? s)
{
if (s is null)
{
return IntPtr.Zero;
}
long lnb = (s.Length + 1) * (long)SystemMaxDBCSCharSize;
int nb = (int)lnb;
// Overflow checking
if (nb != lnb)
{
throw new ArgumentOutOfRangeException(nameof(s));
}
IntPtr hglobal = AllocHGlobal((IntPtr)nb);
StringToAnsiString(s, (byte*)hglobal, nb);
return hglobal;
}
public static unsafe IntPtr StringToHGlobalUni(string? s)
{
if (s is null)
{
return IntPtr.Zero;
}
int nb = (s.Length + 1) * 2;
// Overflow checking
if (nb < s.Length)
{
throw new ArgumentOutOfRangeException(nameof(s));
}
IntPtr hglobal = AllocHGlobal((IntPtr)nb);
fixed (char* firstChar = s)
{
string.wstrcpy((char*)hglobal, firstChar, s.Length + 1);
}
return hglobal;
}
private static unsafe IntPtr StringToHGlobalUTF8(string? s)
{
if (s is null)
{
return IntPtr.Zero;
}
int nb = Encoding.UTF8.GetMaxByteCount(s.Length);
IntPtr pMem = AllocHGlobal(nb + 1);
int nbWritten;
byte* pbMem = (byte*)pMem;
fixed (char* firstChar = s)
{
nbWritten = Encoding.UTF8.GetBytes(firstChar, s.Length, pbMem, nb);
}
pbMem[nbWritten] = 0;
return pMem;
}
public static unsafe IntPtr StringToCoTaskMemUni(string? s)
{
if (s is null)
{
return IntPtr.Zero;
}
int nb = (s.Length + 1) * 2;
// Overflow checking
if (nb < s.Length)
{
throw new ArgumentOutOfRangeException(nameof(s));
}
IntPtr hglobal = AllocCoTaskMem(nb);
fixed (char* firstChar = s)
{
string.wstrcpy((char*)hglobal, firstChar, s.Length + 1);
}
return hglobal;
}
public static unsafe IntPtr StringToCoTaskMemUTF8(string? s)
{
if (s is null)
{
return IntPtr.Zero;
}
int nb = Encoding.UTF8.GetMaxByteCount(s.Length);
IntPtr pMem = AllocCoTaskMem(nb + 1);
int nbWritten;
byte* pbMem = (byte*)pMem;
fixed (char* firstChar = s)
{
nbWritten = Encoding.UTF8.GetBytes(firstChar, s.Length, pbMem, nb);
}
pbMem[nbWritten] = 0;
return pMem;
}
public static unsafe IntPtr StringToCoTaskMemAnsi(string? s)
{
if (s is null)
{
return IntPtr.Zero;
}
long lnb = (s.Length + 1) * (long)SystemMaxDBCSCharSize;
int nb = (int)lnb;
// Overflow checking
if (nb != lnb)
{
throw new ArgumentOutOfRangeException(nameof(s));
}
IntPtr hglobal = AllocCoTaskMem(nb);
StringToAnsiString(s, (byte*)hglobal, nb);
return hglobal;
}
/// <summary>
/// Generates a GUID for the specified type. If the type has a GUID in the
/// metadata then it is returned otherwise a stable guid is generated based
/// on the fully qualified name of the type.
/// </summary>
public static Guid GenerateGuidForType(Type type)
{
if (type is null)
{
throw new ArgumentNullException(nameof(type));
}
if (!type.IsRuntimeImplemented())
{
throw new ArgumentException(SR.Argument_MustBeRuntimeType, nameof(type));
}
return type.GUID;
}
/// <summary>
/// This method generates a PROGID for the specified type. If the type has
/// a PROGID in the metadata then it is returned otherwise a stable PROGID
/// is generated based on the fully qualified name of the type.
/// </summary>
public static string? GenerateProgIdForType(Type type)
{
if (type is null)
{
throw new ArgumentNullException(nameof(type));
}
if (type.IsImport)
{
throw new ArgumentException(SR.Argument_TypeMustNotBeComImport, nameof(type));
}
if (type.IsGenericType)
{
throw new ArgumentException(SR.Argument_NeedNonGenericType, nameof(type));
}
ProgIdAttribute? progIdAttribute = type.GetCustomAttribute<ProgIdAttribute>();
if (progIdAttribute != null)
{
return progIdAttribute.Value ?? string.Empty;
}
// If there is no prog ID attribute then use the full name of the type as the prog id.
return type.FullName;
}
public static Delegate GetDelegateForFunctionPointer(IntPtr ptr, Type t)
{
if (ptr == IntPtr.Zero)
{
throw new ArgumentNullException(nameof(ptr));
}
if (t is null)
{
throw new ArgumentNullException(nameof(t));
}
if (!t.IsRuntimeImplemented())
{
throw new ArgumentException(SR.Argument_MustBeRuntimeType, nameof(t));
}
if (t.IsGenericType)
{
throw new ArgumentException(SR.Argument_NeedNonGenericType, nameof(t));
}
// COMPAT: This block of code isn't entirely correct.
// Users passing in typeof(MulticastDelegate) as 't' skip this check
// since Delegate is a base type of MulticastDelegate.
Type? c = t.BaseType;
if (c != typeof(Delegate) && c != typeof(MulticastDelegate))
{
throw new ArgumentException(SR.Arg_MustBeDelegate, nameof(t));
}
return GetDelegateForFunctionPointerInternal(ptr, t);
}
public static TDelegate GetDelegateForFunctionPointer<TDelegate>(IntPtr ptr)
{
return (TDelegate)(object)GetDelegateForFunctionPointer(ptr, typeof(TDelegate));
}
public static IntPtr GetFunctionPointerForDelegate(Delegate d)
{
if (d is null)
{
throw new ArgumentNullException(nameof(d));
}
return GetFunctionPointerForDelegateInternal(d);
}
public static IntPtr GetFunctionPointerForDelegate<TDelegate>(TDelegate d) where TDelegate : notnull
{
return GetFunctionPointerForDelegate((Delegate)(object)d);
}
public static int GetHRForLastWin32Error()
{
int dwLastError = GetLastWin32Error();
if ((dwLastError & 0x80000000) == 0x80000000)
{
return dwLastError;
}
return (dwLastError & 0x0000FFFF) | unchecked((int)0x80070000);
}
public static unsafe void ZeroFreeBSTR(IntPtr s)
{
if (s == IntPtr.Zero)
{
return;
}
Buffer.ZeroMemory((byte*)s, SysStringByteLen(s));
FreeBSTR(s);
}
public static unsafe void ZeroFreeCoTaskMemAnsi(IntPtr s)
{
ZeroFreeCoTaskMemUTF8(s);
}
public static unsafe void ZeroFreeCoTaskMemUnicode(IntPtr s)
{
if (s == IntPtr.Zero)
{
return;
}
Buffer.ZeroMemory((byte*)s, (nuint)string.wcslen((char*)s) * sizeof(char));
FreeCoTaskMem(s);
}
public static unsafe void ZeroFreeCoTaskMemUTF8(IntPtr s)
{
if (s == IntPtr.Zero)
{
return;
}
Buffer.ZeroMemory((byte*)s, (nuint)string.strlen((byte*)s));
FreeCoTaskMem(s);
}
public static unsafe void ZeroFreeGlobalAllocAnsi(IntPtr s)
{
if (s == IntPtr.Zero)
{
return;
}
Buffer.ZeroMemory((byte*)s, (nuint)string.strlen((byte*)s));
FreeHGlobal(s);
}
public static unsafe void ZeroFreeGlobalAllocUnicode(IntPtr s)
{
if (s == IntPtr.Zero)
{
return;
}
Buffer.ZeroMemory((byte*)s, (nuint)string.wcslen((char*)s) * sizeof(char));
FreeHGlobal(s);
}
internal static unsafe uint SysStringByteLen(IntPtr s)
{
return *(((uint*)s) - 1);
}
}
}