1 // Licensed to the .NET Foundation under one or more agreements.
2 // The .NET Foundation licenses this file to you under the MIT license.
3 // See the LICENSE file in the project root for more information.
6 using System
.Diagnostics
;
7 using System
.Runtime
.InteropServices
;
9 namespace System
.Security
11 internal sealed class SafeBSTRHandle
: SafeBuffer
13 internal SafeBSTRHandle() : base(true) { }
15 internal static SafeBSTRHandle
Allocate(uint lenInChars
)
17 ulong lenInBytes
= (ulong)lenInChars
* sizeof(char);
18 SafeBSTRHandle bstr
= Interop
.OleAut32
.SysAllocStringLen(IntPtr
.Zero
, lenInChars
);
19 if (bstr
.IsInvalid
) // SysAllocStringLen returns a NULL ptr when there's insufficient memory
21 throw new OutOfMemoryException();
23 bstr
.Initialize(lenInBytes
);
27 protected override bool ReleaseHandle()
29 RuntimeImports
.RhZeroMemory(handle
, (UIntPtr
)Marshal
.SysStringByteLen(handle
));
30 Interop
.OleAut32
.SysFreeString(handle
);
34 internal unsafe void ClearBuffer()
36 byte* bufferPtr
= null;
39 AcquirePointer(ref bufferPtr
);
40 RuntimeImports
.RhZeroMemory((IntPtr
)bufferPtr
, (UIntPtr
)Marshal
.SysStringByteLen((IntPtr
)bufferPtr
));
44 if (bufferPtr
!= null)
51 internal unsafe uint Length
=> Interop
.OleAut32
.SysStringLen(this);
53 internal static unsafe void Copy(SafeBSTRHandle source
, SafeBSTRHandle target
, uint bytesToCopy
)
60 byte* sourcePtr
= null, targetPtr
= null;
63 source
.AcquirePointer(ref sourcePtr
);
64 target
.AcquirePointer(ref targetPtr
);
66 Debug
.Assert(source
.ByteLength
>= bytesToCopy
, "Source buffer is too small.");
67 Buffer
.MemoryCopy(sourcePtr
, targetPtr
, target
.ByteLength
, bytesToCopy
);
71 if (targetPtr
!= null)
73 target
.ReleasePointer();
75 if (sourcePtr
!= null)
77 source
.ReleasePointer();