MegaBites-AI/Windows-powershell
0372
1// Copyright (c) Microsoft Corporation.2// Licensed under the MIT License.3 4using System;5using System.Runtime.InteropServices;6 7namespace Microsoft.PowerShell8{9 /// <summary>10 /// Represents the OLE struct PROPVARIANT.11 /// This class is intended for internal use only.12 /// </summary>13 /// <remarks>14 /// Originally sourced from https://blogs.msdn.com/adamroot/pages/interop-with-propvariants-in-net.aspx15 /// and modified to add ability to set values16 /// </remarks>17 [StructLayout(LayoutKind.Explicit)]18 internal sealed class PropVariant : IDisposable19 {20 // This is actually a VarEnum value, but the VarEnum type requires 4 bytes instead of the expected 2.21 [FieldOffset(0)]22 private readonly ushort _valueType;23 24 [FieldOffset(8)]25 private readonly IntPtr _ptr;26 27 /// <summary>28 /// Set a string value.29 /// </summary>30 internal PropVariant(string value)31 {32 if (value == null)33 {34 throw new ArgumentException("PropVariantNullString", nameof(value));35 }36 37 _valueType = (ushort)VarEnum.VT_LPWSTR;38 _ptr = Marshal.StringToCoTaskMemUni(value);39 }40 41 /// <summary>42 /// Disposes the object, calls the clear function.43 /// </summary>44 public void Dispose()45 {46 PropVariantNativeMethods.PropVariantClear(this);47 48 GC.SuppressFinalize(this);49 }50 51 /// <summary>52 /// Finalizes an instance of the <see cref="PropVariant"/> class.53 /// </summary>54 ~PropVariant()55 {56 Dispose();57 }58 59 private static class PropVariantNativeMethods60 {61 [DllImport("Ole32.dll", PreserveSig = false)]62 internal static extern void PropVariantClear([In, Out] PropVariant pvar);63 }64 }65}66 