From e755679c4984895d452f943641a9c6f24827874d Mon Sep 17 00:00:00 2001 From: Hugh Bellamy Date: Thu, 19 Jul 2018 04:29:30 +0100 Subject: [PATCH] Implement GetComObjectData and SetComObjectData (#18900) * Cleanup Marshal.cs * Cleanup __ComObject * Implement GetComObjectData and SetComObjectData * Build fixes * PR feedback and more marshal cleanup * More feedback * Disable corefx tests * Address PR feedback * Fix build breaking typo * Test disable --- .../Runtime/InteropServices/ArrayWithOffset.cs | 30 +- .../System/Runtime/InteropServices/Attributes.cs | 42 +- .../System/Runtime/InteropServices/BStrWrapper.cs | 24 +- .../System/Runtime/InteropServices/COMException.cs | 20 +- .../Runtime/InteropServices/ComMemberType.cs | 5 - .../Runtime/InteropServices/ComTypes/IBindCtx.cs | 14 +- .../InteropServices/ComTypes/IConnectionPoint.cs | 11 - .../ComTypes/IConnectionPointContainer.cs | 13 +- .../ComTypes/IEnumConnectionPoints.cs | 13 +- .../InteropServices/ComTypes/IEnumConnections.cs | 14 +- .../InteropServices/ComTypes/IEnumMoniker.cs | 13 +- .../InteropServices/ComTypes/IEnumString.cs | 13 +- .../InteropServices/ComTypes/IEnumVARIANT.cs | 13 +- .../Runtime/InteropServices/ComTypes/IMoniker.cs | 14 +- .../InteropServices/ComTypes/IPersistFile.cs | 13 +- .../ComTypes/IRunningObjectTable.cs | 13 +- .../Runtime/InteropServices/ComTypes/IStream.cs | 14 +- .../Runtime/InteropServices/ComTypes/ITypeComp.cs | 14 +- .../Runtime/InteropServices/ComTypes/ITypeInfo.cs | 39 +- .../Runtime/InteropServices/ComTypes/ITypeInfo2.cs | 15 +- .../Runtime/InteropServices/ComTypes/ITypeLib.cs | 15 +- .../Runtime/InteropServices/ComTypes/ITypeLib2.cs | 13 +- .../Runtime/InteropServices/CurrencyWrapper.cs | 26 +- .../Runtime/InteropServices/DispatchWrapper.cs | 24 +- .../System/Runtime/InteropServices/ErrorWrapper.cs | 26 +- .../Runtime/InteropServices/Expando/IExpando.cs | 26 +- .../Runtime/InteropServices/ICustomAdapter.cs | 16 +- .../Runtime/InteropServices/ICustomFactory.cs | 5 - .../Runtime/InteropServices/ICustomMarshaler.cs | 15 +- .../InteropServices/ICustomQueryInterface.cs | 25 +- .../InteropServices/InvalidComObjectException.cs | 19 +- .../InvalidOleVariantTypeException.cs | 17 +- .../src/System/Runtime/InteropServices/Marshal.cs | 1116 +++++++++----------- .../InteropServices/NativeCallableAttribute.cs | 25 +- .../Runtime/InteropServices/NativeMethods.cs | 20 +- .../System/Runtime/InteropServices/NonPortable.cs | 88 +- .../System/Runtime/InteropServices/PInvokeMap.cs | 16 +- .../System/Runtime/InteropServices/SEHException.cs | 14 +- .../SafeArrayRankMismatchException.cs | 17 +- .../SafeArrayTypeMismatchException.cs | 18 +- .../Runtime/InteropServices/UnknownWrapper.cs | 23 +- .../Runtime/InteropServices/VariantWrapper.cs | 23 +- .../InteropServices/WindowsRuntime/Attributes.cs | 43 +- .../src/System/__ComObject.cs | 106 +- tests/CoreFX/CoreFX.issues.json | 34 + 45 files changed, 804 insertions(+), 1313 deletions(-) diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/ArrayWithOffset.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/ArrayWithOffset.cs index a9fbc8b..dd2ec7b 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/ArrayWithOffset.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/ArrayWithOffset.cs @@ -2,20 +2,12 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. - -using System; using System.Runtime.CompilerServices; -using System.Runtime.Versioning; namespace System.Runtime.InteropServices { public struct ArrayWithOffset { - //private ArrayWithOffset() - //{ - // throw new Exception(); - //} - public ArrayWithOffset(object array, int offset) { m_array = array; @@ -24,27 +16,15 @@ namespace System.Runtime.InteropServices m_count = CalculateCount(); } - public object GetArray() - { - return m_array; - } + public object GetArray() => m_array; - public int GetOffset() - { - return m_offset; - } + public int GetOffset() => m_offset; - public override int GetHashCode() - { - return m_count + m_offset; - } + public override int GetHashCode() => m_count + m_offset; public override bool Equals(object obj) { - if (obj is ArrayWithOffset) - return Equals((ArrayWithOffset)obj); - else - return false; + return obj is ArrayWithOffset && Equals((ArrayWithOffset)obj); } public bool Equals(ArrayWithOffset obj) @@ -62,7 +42,7 @@ namespace System.Runtime.InteropServices return !(a == b); } - [MethodImplAttribute(MethodImplOptions.InternalCall)] + [MethodImpl(MethodImplOptions.InternalCall)] private extern int CalculateCount(); private object m_array; diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/Attributes.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/Attributes.cs index b99cefc..d1396d7 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/Attributes.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/Attributes.cs @@ -2,13 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -//////////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////////// - -using System; -using System.Reflection; -using System.Diagnostics; - namespace System.Runtime.InteropServices { [AttributeUsage(AttributeTargets.Interface | AttributeTargets.Enum | AttributeTargets.Struct | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] @@ -38,11 +31,13 @@ namespace System.Runtime.InteropServices public sealed class DispIdAttribute : Attribute { internal int _val; + public DispIdAttribute(int dispId) { _val = dispId; } - public int Value { get { return _val; } } + + public int Value => _val; } public enum ComInterfaceType @@ -58,15 +53,18 @@ namespace System.Runtime.InteropServices public sealed class InterfaceTypeAttribute : Attribute { internal ComInterfaceType _val; + public InterfaceTypeAttribute(ComInterfaceType interfaceType) { _val = interfaceType; } + public InterfaceTypeAttribute(short interfaceType) { _val = (ComInterfaceType)interfaceType; } - public ComInterfaceType Value { get { return _val; } } + + public ComInterfaceType Value => _val; } [AttributeUsage(AttributeTargets.Class, Inherited = false)] @@ -79,7 +77,7 @@ namespace System.Runtime.InteropServices _val = defaultInterface; } - public Type Value { get { return _val; } } + public Type Value => _val; } public enum ClassInterfaceType @@ -93,64 +91,77 @@ namespace System.Runtime.InteropServices public sealed class ClassInterfaceAttribute : Attribute { internal ClassInterfaceType _val; + public ClassInterfaceAttribute(ClassInterfaceType classInterfaceType) { _val = classInterfaceType; } + public ClassInterfaceAttribute(short classInterfaceType) { _val = (ClassInterfaceType)classInterfaceType; } - public ClassInterfaceType Value { get { return _val; } } + + public ClassInterfaceType Value => _val; } [AttributeUsage(AttributeTargets.Method, Inherited = false)] public sealed class LCIDConversionAttribute : Attribute { internal int _val; + public LCIDConversionAttribute(int lcid) { _val = lcid; } - public int Value { get { return _val; } } + + public int Value => _val; } [AttributeUsage(AttributeTargets.Class, Inherited = false)] public sealed class ProgIdAttribute : Attribute { internal string _val; + public ProgIdAttribute(string progId) { _val = progId; } - public string Value { get { return _val; } } + + public string Value => _val; } [AttributeUsage(AttributeTargets.Class, Inherited = true)] public sealed class ComSourceInterfacesAttribute : Attribute { internal string _val; + public ComSourceInterfacesAttribute(string sourceInterfaces) { _val = sourceInterfaces; } + public ComSourceInterfacesAttribute(Type sourceInterface) { _val = sourceInterface.FullName; } + public ComSourceInterfacesAttribute(Type sourceInterface1, Type sourceInterface2) { _val = sourceInterface1.FullName + "\0" + sourceInterface2.FullName; } + public ComSourceInterfacesAttribute(Type sourceInterface1, Type sourceInterface2, Type sourceInterface3) { _val = sourceInterface1.FullName + "\0" + sourceInterface2.FullName + "\0" + sourceInterface3.FullName; } + public ComSourceInterfacesAttribute(Type sourceInterface1, Type sourceInterface2, Type sourceInterface3, Type sourceInterface4) { _val = sourceInterface1.FullName + "\0" + sourceInterface2.FullName + "\0" + sourceInterface3.FullName + "\0" + sourceInterface4.FullName; } - public string Value { get { return _val; } } + + public string Value => _val; } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface, Inherited = false)] @@ -171,7 +182,6 @@ namespace System.Runtime.InteropServices _CoClass = coClass; } - public Type CoClass { get { return _CoClass; } } + public Type CoClass => _CoClass; } } - diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/BStrWrapper.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/BStrWrapper.cs index 14a91c9..ae7e6e4 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/BStrWrapper.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/BStrWrapper.cs @@ -2,21 +2,11 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -/*============================================================================= -** -** -** -** Purpose: Wrapper that is converted to a variant with VT_BSTR. -** -** -=============================================================================*/ - - -using System; -using System.Security; - namespace System.Runtime.InteropServices { + /// + /// Wrapper that is converted to a variant with VT_BSTR. + /// public sealed class BStrWrapper { public BStrWrapper(string value) @@ -29,13 +19,7 @@ namespace System.Runtime.InteropServices m_WrappedObject = (string)value; } - public string WrappedObject - { - get - { - return m_WrappedObject; - } - } + public string WrappedObject => m_WrappedObject; private string m_WrappedObject; } diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/COMException.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/COMException.cs index 9f2e055..f1ddf65 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/COMException.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/COMException.cs @@ -2,27 +2,19 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -/*============================================================================= -** -** -** -** Purpose: Exception class for all errors from COM Interop where we don't -** recognize the HResult. -** -** -=============================================================================*/ - -using System; +using System.Runtime.CompilerServices; using System.Runtime.Serialization; using System.Globalization; -using System.Security; -using Microsoft.Win32; namespace System.Runtime.InteropServices { // Exception for COM Interop errors where we don't recognize the HResult. + /// + /// Exception class for all errors from COM Interop where we don't + /// recognize the HResult. + /// [Serializable] - [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] + [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class COMException : ExternalException { public COMException() diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/ComMemberType.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/ComMemberType.cs index 2de0146..4be75b0 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/ComMemberType.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/ComMemberType.cs @@ -2,11 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -//////////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////////// - -using System; - namespace System.Runtime.InteropServices { public enum ComMemberType diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/ComTypes/IBindCtx.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/ComTypes/IBindCtx.cs index c32d66e..a535b94 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/ComTypes/IBindCtx.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/ComTypes/IBindCtx.cs @@ -2,21 +2,9 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -/*============================================================================= -** -** -** -** Purpose: IBindCtx interface definition. -** -** -=============================================================================*/ - -using System; - namespace System.Runtime.InteropServices.ComTypes { [StructLayout(LayoutKind.Sequential)] - public struct BIND_OPTS { public int cbStruct; @@ -26,7 +14,7 @@ namespace System.Runtime.InteropServices.ComTypes } [Guid("0000000e-0000-0000-C000-000000000046")] - [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] + [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] [ComImport] public interface IBindCtx { diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/ComTypes/IConnectionPoint.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/ComTypes/IConnectionPoint.cs index 8e02226..fcca685 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/ComTypes/IConnectionPoint.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/ComTypes/IConnectionPoint.cs @@ -2,17 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -/*============================================================================= -** -** -** -** Purpose: IConnectionPoint interface definition. -** -** -=============================================================================*/ - -using System; - namespace System.Runtime.InteropServices.ComTypes { [Guid("B196B286-BAB4-101A-B69C-00AA00341D07")] diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/ComTypes/IConnectionPointContainer.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/ComTypes/IConnectionPointContainer.cs index 881dd8a..84c590d 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/ComTypes/IConnectionPointContainer.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/ComTypes/IConnectionPointContainer.cs @@ -2,21 +2,10 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -/*============================================================================= -** -** -** -** Purpose: IConnectionPointContainer interface definition. -** -** -=============================================================================*/ - -using System; - namespace System.Runtime.InteropServices.ComTypes { [Guid("B196B284-BAB4-101A-B69C-00AA00341D07")] - [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] + [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] [ComImport] public interface IConnectionPointContainer { diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/ComTypes/IEnumConnectionPoints.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/ComTypes/IEnumConnectionPoints.cs index 32ad1f7..99df6ac 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/ComTypes/IEnumConnectionPoints.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/ComTypes/IEnumConnectionPoints.cs @@ -2,21 +2,10 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -/*============================================================================= -** -** -** -** Purpose: IEnumConnectionPoints interface definition. -** -** -=============================================================================*/ - -using System; - namespace System.Runtime.InteropServices.ComTypes { [Guid("B196B285-BAB4-101A-B69C-00AA00341D07")] - [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] + [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] [ComImport] public interface IEnumConnectionPoints { diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/ComTypes/IEnumConnections.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/ComTypes/IEnumConnections.cs index 418c911..951685b 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/ComTypes/IEnumConnections.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/ComTypes/IEnumConnections.cs @@ -2,21 +2,9 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -/*============================================================================= -** -** -** -** Purpose: IEnumConnections interface definition. -** -** -=============================================================================*/ - -using System; - namespace System.Runtime.InteropServices.ComTypes { [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] - public struct CONNECTDATA { [MarshalAs(UnmanagedType.Interface)] @@ -25,7 +13,7 @@ namespace System.Runtime.InteropServices.ComTypes } [Guid("B196B287-BAB4-101A-B69C-00AA00341D07")] - [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] + [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] [ComImport] public interface IEnumConnections { diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/ComTypes/IEnumMoniker.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/ComTypes/IEnumMoniker.cs index 4513bc8..9a63ba0 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/ComTypes/IEnumMoniker.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/ComTypes/IEnumMoniker.cs @@ -2,21 +2,10 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -/*============================================================================= -** -** -** -** Purpose: IEnumMoniker interface definition. -** -** -=============================================================================*/ - -using System; - namespace System.Runtime.InteropServices.ComTypes { [Guid("00000102-0000-0000-C000-000000000046")] - [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] + [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] [ComImport] public interface IEnumMoniker { diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/ComTypes/IEnumString.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/ComTypes/IEnumString.cs index 0a76e1c..57fc591 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/ComTypes/IEnumString.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/ComTypes/IEnumString.cs @@ -2,21 +2,10 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -/*============================================================================= -** -** -** -** Purpose: IEnumString interface definition. -** -** -=============================================================================*/ - -using System; - namespace System.Runtime.InteropServices.ComTypes { [Guid("00000101-0000-0000-C000-000000000046")] - [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] + [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] [ComImport] public interface IEnumString { diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/ComTypes/IEnumVARIANT.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/ComTypes/IEnumVARIANT.cs index b94ac5e..8440c06 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/ComTypes/IEnumVARIANT.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/ComTypes/IEnumVARIANT.cs @@ -2,21 +2,10 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -/*============================================================================= -** -** -** -** Purpose: IEnumVARIANT interface definition. -** -** -=============================================================================*/ - -using System; - namespace System.Runtime.InteropServices.ComTypes { [Guid("00020404-0000-0000-C000-000000000046")] - [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] + [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] [ComImport] public interface IEnumVARIANT { diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/ComTypes/IMoniker.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/ComTypes/IMoniker.cs index 8072cd2..7a2dd57 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/ComTypes/IMoniker.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/ComTypes/IMoniker.cs @@ -2,21 +2,9 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -/*============================================================================= -** -** -** -** Purpose: IMoniker interface definition. -** -** -=============================================================================*/ - -using System; - namespace System.Runtime.InteropServices.ComTypes { [StructLayout(LayoutKind.Sequential)] - public struct FILETIME { public int dwLowDateTime; @@ -24,7 +12,7 @@ namespace System.Runtime.InteropServices.ComTypes } [Guid("0000000f-0000-0000-C000-000000000046")] - [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] + [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] [ComImport] public interface IMoniker { diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/ComTypes/IPersistFile.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/ComTypes/IPersistFile.cs index ef748f5..cb24d98 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/ComTypes/IPersistFile.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/ComTypes/IPersistFile.cs @@ -2,21 +2,10 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -/*============================================================================= -** -** -** -** Purpose: IPersistFile interface definition. -** -** -=============================================================================*/ - -using System; - namespace System.Runtime.InteropServices.ComTypes { [Guid("0000010b-0000-0000-C000-000000000046")] - [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] + [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] [ComImport] public interface IPersistFile { diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/ComTypes/IRunningObjectTable.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/ComTypes/IRunningObjectTable.cs index bb806e8..1884fcc 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/ComTypes/IRunningObjectTable.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/ComTypes/IRunningObjectTable.cs @@ -2,21 +2,10 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -/*============================================================================= -** -** -** -** Purpose: IRunningObjectTable interface definition. -** -** -=============================================================================*/ - -using System; - namespace System.Runtime.InteropServices.ComTypes { [Guid("00000010-0000-0000-C000-000000000046")] - [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] + [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] [ComImport] public interface IRunningObjectTable { diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/ComTypes/IStream.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/ComTypes/IStream.cs index 7746458..09b2840 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/ComTypes/IStream.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/ComTypes/IStream.cs @@ -2,21 +2,9 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -/*============================================================================= -** -** -** -** Purpose: IStream interface definition. -** -** -=============================================================================*/ - -using System; - namespace System.Runtime.InteropServices.ComTypes { [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] - public struct STATSTG { public string pwcsName; @@ -33,7 +21,7 @@ namespace System.Runtime.InteropServices.ComTypes } [Guid("0000000c-0000-0000-C000-000000000046")] - [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] + [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] [ComImport] public interface IStream { diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/ComTypes/ITypeComp.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/ComTypes/ITypeComp.cs index a05d7af..7e63793 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/ComTypes/ITypeComp.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/ComTypes/ITypeComp.cs @@ -2,17 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -/*============================================================================= -** -** -** -** Purpose: ITypeComp interface definition. -** -** -=============================================================================*/ - -using System; - namespace System.Runtime.InteropServices.ComTypes { public enum DESCKIND @@ -26,7 +15,6 @@ namespace System.Runtime.InteropServices.ComTypes } [StructLayout(LayoutKind.Explicit, CharSet = CharSet.Unicode)] - public struct BINDPTR { [FieldOffset(0)] @@ -38,7 +26,7 @@ namespace System.Runtime.InteropServices.ComTypes } [Guid("00020403-0000-0000-C000-000000000046")] - [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] + [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] [ComImport] public interface ITypeComp { diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/ComTypes/ITypeInfo.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/ComTypes/ITypeInfo.cs index 47faab5..61776e4 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/ComTypes/ITypeInfo.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/ComTypes/ITypeInfo.cs @@ -2,17 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -/*============================================================================= -** -** -** -** Purpose: ITypeInfo interface definition. -** -** -=============================================================================*/ - -using System; - namespace System.Runtime.InteropServices.ComTypes { public enum TYPEKIND @@ -28,7 +17,7 @@ namespace System.Runtime.InteropServices.ComTypes TKIND_MAX = TKIND_UNION + 1 } - [Flags()] + [Flags] public enum TYPEFLAGS : short { TYPEFLAG_FAPPOBJECT = 0x1, @@ -48,7 +37,7 @@ namespace System.Runtime.InteropServices.ComTypes TYPEFLAG_FPROXY = 0x4000 } - [Flags()] + [Flags] public enum IMPLTYPEFLAGS { IMPLTYPEFLAG_FDEFAULT = 0x1, @@ -58,7 +47,6 @@ namespace System.Runtime.InteropServices.ComTypes } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] - public struct TYPEATTR { // Constant used with the memid fields. @@ -86,7 +74,6 @@ namespace System.Runtime.InteropServices.ComTypes } [StructLayout(LayoutKind.Sequential)] - public struct FUNCDESC { public int memid; //MEMBERID memid; @@ -103,7 +90,7 @@ namespace System.Runtime.InteropServices.ComTypes public short wFuncFlags; //WORD wFuncFlags; } - [Flags()] + [Flags] public enum IDLFLAG : short { IDLFLAG_NONE = PARAMFLAG.PARAMFLAG_NONE, @@ -114,14 +101,13 @@ namespace System.Runtime.InteropServices.ComTypes } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] - public struct IDLDESC { public IntPtr dwReserved; public IDLFLAG wIDLFlags; } - [Flags()] + [Flags] public enum PARAMFLAG : short { PARAMFLAG_NONE = 0, @@ -135,7 +121,6 @@ namespace System.Runtime.InteropServices.ComTypes } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] - public struct PARAMDESC { public IntPtr lpVarValue; @@ -143,7 +128,6 @@ namespace System.Runtime.InteropServices.ComTypes } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] - public struct TYPEDESC { public IntPtr lpValue; @@ -151,13 +135,11 @@ namespace System.Runtime.InteropServices.ComTypes } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] - public struct ELEMDESC { public TYPEDESC tdesc; - [System.Runtime.InteropServices.StructLayout(LayoutKind.Explicit, CharSet = CharSet.Unicode)] - + [StructLayout(LayoutKind.Explicit, CharSet = CharSet.Unicode)] public struct DESCUNION { [FieldOffset(0)] @@ -183,8 +165,7 @@ namespace System.Runtime.InteropServices.ComTypes public int memid; public string lpstrSchema; - [System.Runtime.InteropServices.StructLayout(LayoutKind.Explicit, CharSet = CharSet.Unicode)] - + [StructLayout(LayoutKind.Explicit, CharSet = CharSet.Unicode)] public struct DESCUNION { [FieldOffset(0)] @@ -201,7 +182,6 @@ namespace System.Runtime.InteropServices.ComTypes } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] - public struct DISPPARAMS { public IntPtr rgvarg; @@ -211,7 +191,6 @@ namespace System.Runtime.InteropServices.ComTypes } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] - public struct EXCEPINFO { public short wCode; @@ -257,7 +236,7 @@ namespace System.Runtime.InteropServices.ComTypes CC_MAX = 9 } - [Flags()] + [Flags] public enum FUNCFLAGS : short { FUNCFLAG_FRESTRICTED = 0x1, @@ -275,7 +254,7 @@ namespace System.Runtime.InteropServices.ComTypes FUNCFLAG_FIMMEDIATEBIND = 0x1000 } - [Flags()] + [Flags] public enum VARFLAGS : short { VARFLAG_FREADONLY = 0x1, @@ -294,7 +273,7 @@ namespace System.Runtime.InteropServices.ComTypes } [Guid("00020401-0000-0000-C000-000000000046")] - [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] + [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] [ComImport] public interface ITypeInfo { diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/ComTypes/ITypeInfo2.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/ComTypes/ITypeInfo2.cs index 728533c..bad4f6c 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/ComTypes/ITypeInfo2.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/ComTypes/ITypeInfo2.cs @@ -2,21 +2,10 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -/*============================================================================= -** -** -** -** Purpose: ITypeInfo2 interface definition. -** -** -=============================================================================*/ - -using System; - namespace System.Runtime.InteropServices.ComTypes { [Guid("00020412-0000-0000-C000-000000000046")] - [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] + [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] [ComImport] public interface ITypeInfo2 : ITypeInfo { @@ -51,7 +40,7 @@ namespace System.Runtime.InteropServices.ComTypes void GetParamCustData(int indexFunc, int indexParam, ref Guid guid, out object pVarVal); void GetVarCustData(int index, ref Guid guid, out object pVarVal); void GetImplTypeCustData(int index, ref Guid guid, out object pVarVal); - [LCIDConversionAttribute(1)] + [LCIDConversion(1)] void GetDocumentation2(int memid, out string pbstrHelpString, out int pdwHelpStringContext, out string pbstrHelpStringDll); void GetAllCustData(IntPtr pCustData); void GetAllFuncCustData(int index, IntPtr pCustData); diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/ComTypes/ITypeLib.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/ComTypes/ITypeLib.cs index aa4b2d5..6cab58e 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/ComTypes/ITypeLib.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/ComTypes/ITypeLib.cs @@ -2,17 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -/*============================================================================= -** -** -** -** Purpose: ITypeLib interface definition. -** -** -=============================================================================*/ - -using System; - namespace System.Runtime.InteropServices.ComTypes { public enum SYSKIND @@ -23,7 +12,7 @@ namespace System.Runtime.InteropServices.ComTypes SYS_WIN64 = SYS_MAC + 1 } - [Flags()] + [Flags] public enum LIBFLAGS : short { LIBFLAG_FRESTRICTED = 0x1, @@ -44,7 +33,7 @@ namespace System.Runtime.InteropServices.ComTypes } [Guid("00020402-0000-0000-C000-000000000046")] - [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] + [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] [ComImport] public interface ITypeLib { diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/ComTypes/ITypeLib2.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/ComTypes/ITypeLib2.cs index b8f7b83..76ff8a9 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/ComTypes/ITypeLib2.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/ComTypes/ITypeLib2.cs @@ -2,21 +2,10 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -/*============================================================================= -** -** -** -** Purpose: ITypeLib2 interface definition. -** -** -=============================================================================*/ - -using System; - namespace System.Runtime.InteropServices.ComTypes { [Guid("00020411-0000-0000-C000-000000000046")] - [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] + [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] [ComImport] public interface ITypeLib2 : ITypeLib { diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/CurrencyWrapper.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/CurrencyWrapper.cs index 45d8de2..429e65f 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/CurrencyWrapper.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/CurrencyWrapper.cs @@ -2,20 +2,11 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -/*============================================================================= -** -** -** -** Purpose: Wrapper that is converted to a variant with VT_CURRENCY. -** -** -=============================================================================*/ - - -using System; - namespace System.Runtime.InteropServices { + /// + /// Wrapper that is converted to a variant with VT_CURRENCY. + /// public sealed class CurrencyWrapper { public CurrencyWrapper(decimal obj) @@ -26,17 +17,14 @@ namespace System.Runtime.InteropServices public CurrencyWrapper(object obj) { if (!(obj is decimal)) + { throw new ArgumentException(SR.Arg_MustBeDecimal, nameof(obj)); + } + m_WrappedObject = (decimal)obj; } - public decimal WrappedObject - { - get - { - return m_WrappedObject; - } - } + public decimal WrappedObject => m_WrappedObject; private decimal m_WrappedObject; } diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/DispatchWrapper.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/DispatchWrapper.cs index 1007462..b96ba43 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/DispatchWrapper.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/DispatchWrapper.cs @@ -2,21 +2,11 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -/*============================================================================= -** -** -** -** Purpose: Wrapper that is converted to a variant with VT_DISPATCH. -** -** -=============================================================================*/ - - -using System; -using System.Security; - namespace System.Runtime.InteropServices { + /// + /// Wrapper that is converted to a variant with VT_DISPATCH. + /// public sealed class DispatchWrapper { public DispatchWrapper(object obj) @@ -32,13 +22,7 @@ namespace System.Runtime.InteropServices m_WrappedObject = obj; } - public object WrappedObject - { - get - { - return m_WrappedObject; - } - } + public object WrappedObject => m_WrappedObject; private object m_WrappedObject; } diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/ErrorWrapper.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/ErrorWrapper.cs index de249f4..af139f8 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/ErrorWrapper.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/ErrorWrapper.cs @@ -2,20 +2,11 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -/*============================================================================= -** -** -** -** Purpose: Wrapper that is converted to a variant with VT_ERROR. -** -** -=============================================================================*/ - - -using System; - namespace System.Runtime.InteropServices { + /// + /// Wrapper that is converted to a variant with VT_ERROR. + /// public sealed class ErrorWrapper { public ErrorWrapper(int errorCode) @@ -26,7 +17,10 @@ namespace System.Runtime.InteropServices public ErrorWrapper(object errorCode) { if (!(errorCode is int)) + { throw new ArgumentException(SR.Arg_MustBeInt32, nameof(errorCode)); + } + m_ErrorCode = (int)errorCode; } @@ -35,13 +29,7 @@ namespace System.Runtime.InteropServices m_ErrorCode = Marshal.GetHRForException(e); } - public int ErrorCode - { - get - { - return m_ErrorCode; - } - } + public int ErrorCode => m_ErrorCode; private int m_ErrorCode; } diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/Expando/IExpando.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/Expando/IExpando.cs index 7cfbd94..909aac1 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/Expando/IExpando.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/Expando/IExpando.cs @@ -2,29 +2,27 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -//////////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////////// -// -// IExpando is an interface which allows Objects implemeningt this interface -// support the ability to modify the object by adding and removing members, -// represented by MemberInfo objects. -// -// -// The IExpando Interface. - -using System; using System.Reflection; namespace System.Runtime.InteropServices.Expando { + /// + /// IExpando is an interface which allows Objects implementing this interface to + /// support the ability to modify the object by adding and removing members, + /// represented by MemberInfo objects. + /// [Guid("AFBF15E6-C37C-11d2-B88E-00A0C9B471B8")] internal interface IExpando : IReflect { - // Add a new Field to the reflection object. The field has - // name as its name. + /// + /// Add a new Field to the reflection object. The field has + /// name as its name. + /// FieldInfo AddField(string name); - // Removes the specified member. + /// + /// Removes the specified member. + /// void RemoveMember(MemberInfo m); } } diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/ICustomAdapter.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/ICustomAdapter.cs index 934b9e2..9ef3400 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/ICustomAdapter.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/ICustomAdapter.cs @@ -2,20 +2,12 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -/*============================================================================= -** -** -** -** Purpose: This the base interface that custom adapters can chose to implement -** when they want to expose the underlying object. -** -** -=============================================================================*/ - -using System; - namespace System.Runtime.InteropServices { + /// + /// The base interface that custom adapters can chose to implement + /// when they want to expose the underlying object. + /// public interface ICustomAdapter { [return: MarshalAs(UnmanagedType.IUnknown)] object GetUnderlyingObject(); diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/ICustomFactory.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/ICustomFactory.cs index e7bfc47..799db6a 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/ICustomFactory.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/ICustomFactory.cs @@ -2,11 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -//////////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////////// - -using System; - namespace System.Runtime.InteropServices { public interface ICustomFactory diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/ICustomMarshaler.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/ICustomMarshaler.cs index c1cae83..1643045 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/ICustomMarshaler.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/ICustomMarshaler.cs @@ -2,20 +2,11 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -/*============================================================================= -** -** -** -** Purpose: This the base interface that must be implemented by all custom -** marshalers. -** -** -=============================================================================*/ - -using System; - namespace System.Runtime.InteropServices { + /// + /// The base interface that must be implemented by all custom marshalers. + /// public interface ICustomMarshaler { object MarshalNativeToManaged(IntPtr pNativeData); diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/ICustomQueryInterface.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/ICustomQueryInterface.cs index f0aa35e..b0e6534 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/ICustomQueryInterface.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/ICustomQueryInterface.cs @@ -2,23 +2,11 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -/*============================================================================= -** -** -** -** Purpose: This the interface that be implemented by class that want to -** customize the behavior of QueryInterface. -** -** -=============================================================================*/ - -using System; - namespace System.Runtime.InteropServices { - //==================================================================== - // The enum of the return value of IQuerable.GetInterface - //==================================================================== + /// + /// The enum of the return value of IQuerable.GetInterface. + /// public enum CustomQueryInterfaceResult { Handled = 0, @@ -26,9 +14,10 @@ namespace System.Runtime.InteropServices Failed = 2, } - //==================================================================== - // The interface for customizing IQueryInterface - //==================================================================== + /// + /// the interface that be implemented by class that want to + /// customize the behavior of QueryInterface. + /// public interface ICustomQueryInterface { CustomQueryInterfaceResult GetInterface([In]ref Guid iid, out IntPtr ppv); diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/InvalidComObjectException.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/InvalidComObjectException.cs index f9bea3f..02f1728 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/InvalidComObjectException.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/InvalidComObjectException.cs @@ -2,23 +2,18 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -/*============================================================================= -** -** -** Purpose: This exception is thrown when an invalid COM object is used. This -** happens when a the __ComObject type is used directly without -** having a backing class factory. -** -=============================================================================*/ - - -using System; +using System.Runtime.CompilerServices; using System.Runtime.Serialization; namespace System.Runtime.InteropServices { + /// + /// The exception thrown when an invalid COM object is used. This happens + /// when a the __ComObject type is used directly without having a backing + /// class factory. + /// [Serializable] - [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] + [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class InvalidComObjectException : SystemException { public InvalidComObjectException() diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/InvalidOleVariantTypeException.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/InvalidOleVariantTypeException.cs index 1a4abbb..9ec47dd 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/InvalidOleVariantTypeException.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/InvalidOleVariantTypeException.cs @@ -2,22 +2,17 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -/*============================================================================= -** -** -** Purpose: The type of an OLE variant that was passed into the runtime is -** invalid. -** -=============================================================================*/ - - -using System; +using System.Runtime.CompilerServices; using System.Runtime.Serialization; namespace System.Runtime.InteropServices { + /// + /// Exception thrown when the type of an OLE variant that was passed into the + /// runtime is invalid. + /// [Serializable] - [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] + [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class InvalidOleVariantTypeException : SystemException { public InvalidOleVariantTypeException() diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/Marshal.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/Marshal.cs index 40b934c..74d1e6e 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/Marshal.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/Marshal.cs @@ -2,57 +2,36 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -/*============================================================================= -** -** -** -** Purpose: This class contains methods that are mainly used to marshal -** between unmanaged and managed types. -** -** -=============================================================================*/ +using System.Collections.Generic; +using System.Reflection; +using System.Reflection.Emit; +using System.Security; +using System.Text; +using System.Runtime.CompilerServices; +using System.Runtime.ConstrainedExecution; +using Win32Native = Microsoft.Win32.Win32Native; +using System.Diagnostics; +using System.Runtime.InteropServices.ComTypes; +using System.StubHelpers; namespace System.Runtime.InteropServices { - using System; - using System.Runtime; - using System.Collections.Generic; - using System.Reflection; - using System.Reflection.Emit; - using System.Security; - using System.Text; - using System.Threading; - using System.Runtime.CompilerServices; - using System.Globalization; - using System.Runtime.ConstrainedExecution; - using System.Runtime.Versioning; - using Win32Native = Microsoft.Win32.Win32Native; - using Microsoft.Win32.SafeHandles; - using System.Diagnostics; - using System.Runtime.InteropServices.ComTypes; - using System.StubHelpers; - public enum CustomQueryInterfaceMode { Ignore = 0, Allow = 1 } - //======================================================================== - // All public methods, including PInvoke, are protected with linkchecks. - // Remove the default demands for all PInvoke methods with this global - // declaration on the class. - //======================================================================== - + /// + /// This class contains methods that are mainly used to marshal between unmanaged + /// and managed types. + /// public static partial class Marshal { - //==================================================================== - // Defines used inside the Marshal class. - //==================================================================== private const int LMEM_FIXED = 0; private const int LMEM_MOVEABLE = 2; #if !FEATURE_PAL - private const long HIWORDMASK = unchecked((long)0xffffffffffff0000L); + private const long HiWordMask = unchecked((long)0xffffffffffff0000L); #endif //!FEATURE_PAL #if FEATURE_COMINTEROP private static Guid IID_IUnknown = new Guid("00000000-0000-0000-C000-000000000046"); @@ -70,46 +49,25 @@ namespace System.Runtime.InteropServices return false; #else long lPtr = (long)ptr; - return 0 == (lPtr & HIWORDMASK); -#endif - } - - private static bool IsNotWin32Atom(IntPtr ptr) - { -#if FEATURE_PAL - return true; -#else - long lPtr = (long)ptr; - return 0 != (lPtr & HIWORDMASK); + return 0 == (lPtr & HiWordMask); #endif } - //==================================================================== - // The default character size for the system. This is always 2 because - // the framework only runs on UTF-16 systems. - //==================================================================== + /// + /// The default character size for the system. This is always 2 because + /// the framework only runs on UTF-16 systems. + /// public static readonly int SystemDefaultCharSize = 2; - //==================================================================== - // The max DBCS character size for the system. - //==================================================================== + /// + /// The max DBCS character size for the system. + /// public static readonly int SystemMaxDBCSCharSize = GetSystemMaxDBCSCharSize(); - - //==================================================================== - // The name, title and description of the assembly that will contain - // the dynamically generated interop types. - //==================================================================== - private const string s_strConvertedTypeInfoAssemblyName = "InteropDynamicTypes"; - private const string s_strConvertedTypeInfoAssemblyTitle = "Interop Dynamic Types"; - private const string s_strConvertedTypeInfoAssemblyDesc = "Type dynamically generated from ITypeInfo's"; - private const string s_strConvertedTypeInfoNameSpace = "InteropDynamicTypes"; - - - //==================================================================== - // Helper method to retrieve the system's maximum DBCS character size. - //==================================================================== - [MethodImplAttribute(MethodImplOptions.InternalCall)] + /// + /// Helper method to retrieve the system's maximum DBCS character size. + /// + [MethodImpl(MethodImplOptions.InternalCall)] private static extern int GetSystemMaxDBCSCharSize(); public static unsafe string PtrToStringAnsi(IntPtr ptr) @@ -122,26 +80,26 @@ namespace System.Runtime.InteropServices { return null; } - else + + int nb = Win32Native.lstrlenA(ptr); + if (nb == 0) { - int nb = Win32Native.lstrlenA(ptr); - if (nb == 0) - { - return string.Empty; - } - else - { - return new string((sbyte*)ptr); - } + return string.Empty; } + + 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 ArgumentException(null, nameof(len)); + } return new string((sbyte*)ptr, 0, len); } @@ -149,9 +107,13 @@ namespace System.Runtime.InteropServices public static unsafe string PtrToStringUni(IntPtr ptr, int len) { if (ptr == IntPtr.Zero) + { throw new ArgumentNullException(nameof(ptr)); + } if (len < 0) - throw new ArgumentException(null, nameof(len)); + { + throw new ArgumentException(SR.ArgumentOutOfRange_NeedNonNegNum, nameof(len)); + } return new string((char*)ptr, 0, len); } @@ -172,10 +134,8 @@ namespace System.Runtime.InteropServices { return null; } - else - { - return new string((char*)ptr); - } + + return new string((char*)ptr); } public static string PtrToStringAuto(IntPtr ptr) @@ -190,11 +150,9 @@ namespace System.Runtime.InteropServices { return null; } - else - { - int nbBytes = System.StubHelpers.StubHelpers.strlen((sbyte*)ptr.ToPointer()); - return PtrToStringUTF8(ptr, nbBytes); - } + + int nbBytes = StubHelpers.StubHelpers.strlen((sbyte*)ptr.ToPointer()); + return PtrToStringUTF8(ptr, nbBytes); } public static unsafe string PtrToStringUTF8(IntPtr ptr, int byteLen) @@ -215,84 +173,78 @@ namespace System.Runtime.InteropServices { return string.Empty; } - else - { - byte* pByte = (byte*)ptr.ToPointer(); - return Encoding.UTF8.GetString(pByte, byteLen); - } + + byte* pByte = (byte*)ptr.ToPointer(); + return Encoding.UTF8.GetString(pByte, byteLen); } - //==================================================================== - // SizeOf() - //==================================================================== public static int SizeOf(object structure) { if (structure == null) + { throw new ArgumentNullException(nameof(structure)); - // we never had a check for generics here + } return SizeOfHelper(structure.GetType(), true); } - public static int SizeOf(T structure) - { - return SizeOf((object)structure); - } + public static int SizeOf(T structure) => SizeOf((object)structure); public static int SizeOf(Type t) { if (t == null) + { throw new ArgumentNullException(nameof(t)); + } if (!(t is RuntimeType)) + { throw new ArgumentException(SR.Argument_MustBeRuntimeType, nameof(t)); + } if (t.IsGenericType) + { throw new ArgumentException(SR.Argument_NeedNonGenericType, nameof(t)); + } - return SizeOfHelper(t, true); + return SizeOfHelper(t, throwIfNotMarshalable: true); } - public static int SizeOf() - { - return SizeOf(typeof(T)); - } + public static int SizeOf() => SizeOf(typeof(T)); - [MethodImplAttribute(MethodImplOptions.InternalCall)] + [MethodImpl(MethodImplOptions.InternalCall)] internal static extern int SizeOfHelper(Type t, bool throwIfNotMarshalable); - //==================================================================== - // OffsetOf() - //==================================================================== public static IntPtr OffsetOf(Type t, string fieldName) { if (t == null) + { throw new ArgumentNullException(nameof(t)); + } FieldInfo f = t.GetField(fieldName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); if (f == null) + { throw new ArgumentException(SR.Format(SR.Argument_OffsetOfFieldNotFound, t.FullName), nameof(fieldName)); - RtFieldInfo rtField = f as RtFieldInfo; - if (rtField == null) + } + + if (!(f is RtFieldInfo rtField)) + { throw new ArgumentException(SR.Argument_MustBeRuntimeFieldInfo, nameof(fieldName)); + } return OffsetOfHelper(rtField); } - public static IntPtr OffsetOf(string fieldName) - { - return OffsetOf(typeof(T), fieldName); - } - [MethodImplAttribute(MethodImplOptions.InternalCall)] + public static IntPtr OffsetOf(string fieldName) => OffsetOf(typeof(T), fieldName); + + [MethodImpl(MethodImplOptions.InternalCall)] private static extern IntPtr OffsetOfHelper(IRuntimeFieldInfo f); - //==================================================================== - // UnsafeAddrOfPinnedArrayElement() - // - // IMPORTANT NOTICE: This method does not do any verification on the - // array. It must be used with EXTREME CAUTION since passing in - // an array that is not pinned or in the fixed heap can cause - // unexpected results ! - //==================================================================== - [MethodImplAttribute(MethodImplOptions.InternalCall)] + /// + /// IMPORTANT NOTICE: This method does not do any verification on the array. + /// It must be used with EXTREME CAUTION since passing in an array that is + /// not pinned or in the fixed heap can cause unexpected results. + /// + [MethodImpl(MethodImplOptions.InternalCall)] public static extern IntPtr UnsafeAddrOfPinnedArrayElement(Array arr, int index); public static IntPtr UnsafeAddrOfPinnedArrayElement(T[] arr, int index) @@ -300,88 +252,95 @@ namespace System.Runtime.InteropServices return UnsafeAddrOfPinnedArrayElement((Array)arr, index); } - //==================================================================== - // Copy blocks from CLR arrays to native memory. - //==================================================================== 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); } - [MethodImplAttribute(MethodImplOptions.InternalCall)] + + [MethodImpl(MethodImplOptions.InternalCall)] private static extern void CopyToNative(object source, int startIndex, IntPtr destination, int length); - //==================================================================== - // Copy blocks from native memory to CLR arrays - //==================================================================== 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); } - [MethodImplAttribute(MethodImplOptions.InternalCall)] - private static extern void CopyToManaged(IntPtr source, object destination, int startIndex, int length); - //==================================================================== - // Read from memory - //==================================================================== + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void CopyToManaged(IntPtr source, object destination, int startIndex, int length); + public static byte ReadByte(object ptr, int ofs) { - return ReadValueSlow(ptr, ofs, (IntPtr nativeHome, int offset) => Marshal.ReadByte(nativeHome, offset)); + return ReadValueSlow(ptr, ofs, (IntPtr nativeHome, int offset) => ReadByte(nativeHome, offset)); } public static unsafe byte ReadByte(IntPtr ptr, int ofs) @@ -398,14 +357,11 @@ namespace System.Runtime.InteropServices } } - public static byte ReadByte(IntPtr ptr) - { - return ReadByte(ptr, 0); - } + public static byte ReadByte(IntPtr ptr) => ReadByte(ptr, 0); public static short ReadInt16(object ptr, int ofs) { - return ReadValueSlow(ptr, ofs, (IntPtr nativeHome, int offset) => Marshal.ReadInt16(nativeHome, offset)); + return ReadValueSlow(ptr, ofs, (IntPtr nativeHome, int offset) => ReadInt16(nativeHome, offset)); } public static unsafe short ReadInt16(IntPtr ptr, int ofs) @@ -435,14 +391,11 @@ namespace System.Runtime.InteropServices } } - public static short ReadInt16(IntPtr ptr) - { - return ReadInt16(ptr, 0); - } + public static short ReadInt16(IntPtr ptr) => ReadInt16(ptr, 0); public static int ReadInt32(object ptr, int ofs) { - return ReadValueSlow(ptr, ofs, (IntPtr nativeHome, int offset) => Marshal.ReadInt32(nativeHome, offset)); + return ReadValueSlow(ptr, ofs, (IntPtr nativeHome, int offset) => ReadInt32(nativeHome, offset)); } public static unsafe int ReadInt32(IntPtr ptr, int ofs) @@ -474,10 +427,7 @@ namespace System.Runtime.InteropServices } } - public static int ReadInt32(IntPtr ptr) - { - return ReadInt32(ptr, 0); - } + public static int ReadInt32(IntPtr ptr) => ReadInt32(ptr, 0); public static IntPtr ReadIntPtr(object ptr, int ofs) { @@ -497,18 +447,11 @@ namespace System.Runtime.InteropServices #endif } - public static IntPtr ReadIntPtr(IntPtr ptr) - { -#if BIT64 - return (IntPtr)ReadInt64(ptr, 0); -#else // 32 - return (IntPtr)ReadInt32(ptr, 0); -#endif - } + public static IntPtr ReadIntPtr(IntPtr ptr) => ReadIntPtr(ptr, 0); public static long ReadInt64([MarshalAs(UnmanagedType.AsAny), In] object ptr, int ofs) { - return ReadValueSlow(ptr, ofs, (IntPtr nativeHome, int offset) => Marshal.ReadInt64(nativeHome, offset)); + return ReadValueSlow(ptr, ofs, (IntPtr nativeHome, int offset) => ReadInt64(nativeHome, offset)); } public static unsafe long ReadInt64(IntPtr ptr, int ofs) @@ -544,10 +487,7 @@ namespace System.Runtime.InteropServices } } - public static long ReadInt64(IntPtr ptr) - { - return ReadInt64(ptr, 0); - } + public static long ReadInt64(IntPtr ptr) => ReadInt64(ptr, 0); //==================================================================== // Read value from marshaled object (marshaled using AsAny) @@ -559,9 +499,11 @@ namespace System.Runtime.InteropServices { // Consumers of this method are documented to throw AccessViolationException on any AV if (ptr == null) + { throw new AccessViolationException(); + } - int dwFlags = + const int Flags = (int)AsAnyMarshaler.AsAnyFlags.In | (int)AsAnyMarshaler.AsAnyFlags.IsAnsi | (int)AsAnyMarshaler.AsAnyFlags.IsBestFit; @@ -573,7 +515,7 @@ namespace System.Runtime.InteropServices try { - pNativeHome = marshaler.ConvertToNative(ptr, dwFlags); + pNativeHome = marshaler.ConvertToNative(ptr, Flags); return readValueHelper(pNativeHome, ofs); } finally @@ -582,9 +524,6 @@ namespace System.Runtime.InteropServices } } - //==================================================================== - // Write to memory - //==================================================================== public static unsafe void WriteByte(IntPtr ptr, int ofs, byte val) { try @@ -601,13 +540,10 @@ namespace System.Runtime.InteropServices public static void WriteByte(object ptr, int ofs, byte val) { - WriteValueSlow(ptr, ofs, val, (IntPtr nativeHome, int offset, byte value) => Marshal.WriteByte(nativeHome, offset, value)); + WriteValueSlow(ptr, ofs, val, (IntPtr nativeHome, int offset, byte value) => WriteByte(nativeHome, offset, value)); } - public static void WriteByte(IntPtr ptr, byte val) - { - WriteByte(ptr, 0, val); - } + public static void WriteByte(IntPtr ptr, byte val) => WriteByte(ptr, 0, val); public static unsafe void WriteInt16(IntPtr ptr, int ofs, short val) { @@ -639,25 +575,13 @@ namespace System.Runtime.InteropServices WriteValueSlow(ptr, ofs, val, (IntPtr nativeHome, int offset, short value) => Marshal.WriteInt16(nativeHome, offset, value)); } - public static void WriteInt16(IntPtr ptr, short val) - { - WriteInt16(ptr, 0, val); - } + 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(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([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 void WriteInt16(IntPtr ptr, char val) => WriteInt16(ptr, 0, (short)val); public static unsafe void WriteInt32(IntPtr ptr, int ofs, int val) { @@ -691,10 +615,7 @@ namespace System.Runtime.InteropServices WriteValueSlow(ptr, ofs, val, (IntPtr nativeHome, int offset, int value) => Marshal.WriteInt32(nativeHome, offset, value)); } - public static void WriteInt32(IntPtr ptr, int val) - { - WriteInt32(ptr, 0, val); - } + public static void WriteInt32(IntPtr ptr, int val) => WriteInt32(ptr, 0, val); public static void WriteIntPtr(IntPtr ptr, int ofs, IntPtr val) { @@ -714,14 +635,7 @@ namespace System.Runtime.InteropServices #endif } - public static void WriteIntPtr(IntPtr ptr, IntPtr val) - { -#if BIT64 - WriteInt64(ptr, 0, (long)val); -#else // 32 - WriteInt32(ptr, 0, (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) { @@ -759,25 +673,22 @@ namespace System.Runtime.InteropServices WriteValueSlow(ptr, ofs, val, (IntPtr nativeHome, int offset, long value) => Marshal.WriteInt64(nativeHome, offset, value)); } - public static void WriteInt64(IntPtr ptr, long val) - { - WriteInt64(ptr, 0, val); - } + public static void WriteInt64(IntPtr ptr, long val) => WriteInt64(ptr, 0, val); - //==================================================================== - // Write value into marshaled object (marshaled using AsAny) and - // propagate the value back - // It's quite slow and can return back dangling pointers - // It's only there for backcompact - // People should instead use the IntPtr overloads - //==================================================================== + /// + /// Write value into marshaled object (marshaled using AsAny) and propagate the + /// value back. This is quite slow and can return back dangling pointers. It is + /// only here for backcompat. People should instead use the IntPtr overloads. + /// private static unsafe void WriteValueSlow(object ptr, int ofs, T val, Action writeValueHelper) { // Consumers of this method are documented to throw AccessViolationException on any AV if (ptr == null) + { throw new AccessViolationException(); + } - int dwFlags = + const int Flags = (int)AsAnyMarshaler.AsAnyFlags.In | (int)AsAnyMarshaler.AsAnyFlags.Out | (int)AsAnyMarshaler.AsAnyFlags.IsAnsi | @@ -790,7 +701,7 @@ namespace System.Runtime.InteropServices try { - pNativeHome = marshaler.ConvertToNative(ptr, dwFlags); + pNativeHome = marshaler.ConvertToNative(ptr, Flags); writeValueHelper(pNativeHome, ofs, val); marshaler.ConvertToManaged(ptr, pNativeHome); } @@ -800,45 +711,33 @@ namespace System.Runtime.InteropServices } } - //==================================================================== - // GetLastWin32Error - //==================================================================== - [MethodImplAttribute(MethodImplOptions.InternalCall)] + [MethodImpl(MethodImplOptions.InternalCall)] public static extern int GetLastWin32Error(); - - //==================================================================== - // SetLastWin32Error - //==================================================================== - [MethodImplAttribute(MethodImplOptions.InternalCall)] + [MethodImpl(MethodImplOptions.InternalCall)] internal static extern void SetLastWin32Error(int error); - - //==================================================================== - // GetHRForLastWin32Error - //==================================================================== public static int GetHRForLastWin32Error() { int dwLastError = GetLastWin32Error(); if ((dwLastError & 0x80000000) == 0x80000000) + { return dwLastError; - else - return (dwLastError & 0x0000FFFF) | unchecked((int)0x80070000); + } + + return (dwLastError & 0x0000FFFF) | unchecked((int)0x80070000); } - - //==================================================================== - // Prelink - //==================================================================== public static void Prelink(MethodInfo m) { if (m == null) + { throw new ArgumentNullException(nameof(m)); - - RuntimeMethodInfo rmi = m as RuntimeMethodInfo; - - if (rmi == null) - throw new ArgumentException(SR.Argument_MustBeRuntimeMethodInfo); + } + if (!(m is RuntimeMethodInfo rmi)) + { + throw new ArgumentException(SR.Argument_MustBeRuntimeMethodInfo, nameof(m)); + } InternalPrelink(rmi); } @@ -849,7 +748,9 @@ namespace System.Runtime.InteropServices public static void PrelinkAll(Type c) { if (c == null) + { throw new ArgumentNullException(nameof(c)); + } MethodInfo[] mi = c.GetMethods(); if (mi != null) @@ -861,19 +762,18 @@ namespace System.Runtime.InteropServices } } - [MethodImplAttribute(MethodImplOptions.InternalCall)] + [MethodImpl(MethodImplOptions.InternalCall)] public static extern /* struct _EXCEPTION_POINTERS* */ IntPtr GetExceptionPointers(); - [MethodImplAttribute(MethodImplOptions.InternalCall)] + [MethodImpl(MethodImplOptions.InternalCall)] public static extern int GetExceptionCode(); - - //==================================================================== - // Marshals data from a structure class to a native memory block. - // If the structure contains pointers to allocated blocks and - // "fDeleteOld" is true, this routine will call DestroyStructure() first. - //==================================================================== - [MethodImplAttribute(MethodImplOptions.InternalCall), ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] + /// + /// Marshals data from a structure class to a native memory block. If the + /// structure contains pointers to allocated blocks and "fDeleteOld" is + /// true, this routine will call DestroyStructure() first. + /// + [MethodImpl(MethodImplOptions.InternalCall), ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] public static extern void StructureToPtr(object structure, IntPtr ptr, bool fDeleteOld); public static void StructureToPtr(T structure, IntPtr ptr, bool fDeleteOld) @@ -881,12 +781,12 @@ namespace System.Runtime.InteropServices StructureToPtr((object)structure, ptr, fDeleteOld); } - //==================================================================== - // Marshals data from a native memory block to a preallocated structure class. - //==================================================================== + /// + /// Marshals data from a native memory block to a preallocated structure class. + /// public static void PtrToStructure(IntPtr ptr, object structure) { - PtrToStructureHelper(ptr, structure, false); + PtrToStructureHelper(ptr, structure, allowValueClasses: false); } public static void PtrToStructure(IntPtr ptr, T structure) @@ -894,75 +794,74 @@ namespace System.Runtime.InteropServices PtrToStructure(ptr, (object)structure); } - //==================================================================== - // Creates a new instance of "structuretype" and marshals data from a - // native memory block to it. - //==================================================================== + /// + /// Creates a new instance of "structuretype" and marshals data from a + /// native memory block to it. + /// public static object PtrToStructure(IntPtr ptr, Type structureType) { - if (ptr == IntPtr.Zero) return null; + if (ptr == IntPtr.Zero) + { + return null; + } if (structureType == null) + { throw new ArgumentNullException(nameof(structureType)); - + } if (structureType.IsGenericType) + { throw new ArgumentException(SR.Argument_NeedNonGenericType, nameof(structureType)); - - RuntimeType rt = structureType.UnderlyingSystemType as RuntimeType; - - if (rt == null) + } + if (!(structureType.UnderlyingSystemType is RuntimeType rt)) + { throw new ArgumentException(SR.Arg_MustBeType, nameof(structureType)); + } - object structure = rt.CreateInstanceDefaultCtor(false /*publicOnly*/, false /*skipCheckThis*/, false /*fillCache*/, true /*wrapExceptions*/); - PtrToStructureHelper(ptr, structure, true); + object structure = rt.CreateInstanceDefaultCtor(publicOnly: false, skipCheckThis: false, fillCache: false, wrapExceptions: true); + PtrToStructureHelper(ptr, structure, allowValueClasses: true); return structure; } - public static T PtrToStructure(IntPtr ptr) - { - return (T)PtrToStructure(ptr, typeof(T)); - } + public static T PtrToStructure(IntPtr ptr) => (T)PtrToStructure(ptr, typeof(T)); - //==================================================================== - // Helper function to copy a pointer into a preallocated structure. - //==================================================================== - [MethodImplAttribute(MethodImplOptions.InternalCall)] + /// + /// Helper function to copy a pointer into a preallocated structure. + /// + [MethodImpl(MethodImplOptions.InternalCall)] private static extern void PtrToStructureHelper(IntPtr ptr, object structure, bool allowValueClasses); - - //==================================================================== - // Freeds all substructures pointed to by the native memory block. - // "structureclass" is used to provide layout information. - //==================================================================== - [MethodImplAttribute(MethodImplOptions.InternalCall)] + /// + /// Frees all substructures pointed to by the native memory block. + /// "structuretype" is used to provide layout information. + /// + [MethodImpl(MethodImplOptions.InternalCall)] public static extern void DestroyStructure(IntPtr ptr, Type structuretype); - public static void DestroyStructure(IntPtr ptr) - { - DestroyStructure(ptr, typeof(T)); - } + public static void DestroyStructure(IntPtr ptr) => DestroyStructure(ptr, typeof(T)); #if FEATURE_COMINTEROP - //==================================================================== - // Returns the HInstance for this module. Returns -1 if the module - // doesn't have an HInstance. In Memory (Dynamic) Modules won't have - // an HInstance. - //==================================================================== + /// + /// Returns the HInstance for this module. Returns -1 if the module doesn't have + /// an HInstance. In Memory (Dynamic) Modules won't have an HInstance. + /// public static IntPtr GetHINSTANCE(Module m) { if (m == null) + { throw new ArgumentNullException(nameof(m)); + } RuntimeModule rtModule = m as RuntimeModule; - if (rtModule == null) + if (rtModule == null && m is ModuleBuilder mb) { - ModuleBuilder mb = m as ModuleBuilder; - if (mb != null) - rtModule = mb.InternalModule; + rtModule = mb.InternalModule; } if (rtModule == null) + { throw new ArgumentNullException(nameof(m), SR.Argument_MustBeRuntimeModule); + } return GetHINSTANCE(rtModule.GetNativeHandle()); } @@ -971,49 +870,54 @@ namespace System.Runtime.InteropServices private static extern IntPtr GetHINSTANCE(RuntimeModule m); #endif // FEATURE_COMINTEROP - //==================================================================== - // Throws a CLR exception based on the HRESULT. - //==================================================================== + + /// + /// Throws a CLR exception based on the HRESULT. + /// public static void ThrowExceptionForHR(int errorCode) { if (errorCode < 0) + { ThrowExceptionForHRInternal(errorCode, IntPtr.Zero); + } } + public static void ThrowExceptionForHR(int errorCode, IntPtr errorInfo) { if (errorCode < 0) + { ThrowExceptionForHRInternal(errorCode, errorInfo); + } } - [MethodImplAttribute(MethodImplOptions.InternalCall)] + [MethodImpl(MethodImplOptions.InternalCall)] internal static extern void ThrowExceptionForHRInternal(int errorCode, IntPtr errorInfo); - - //==================================================================== - // Converts the HRESULT to a CLR exception. - //==================================================================== + /// + /// Converts the HRESULT to a CLR exception. + /// public static Exception GetExceptionForHR(int errorCode) { - if (errorCode < 0) - return GetExceptionForHRInternal(errorCode, IntPtr.Zero); - else + if (errorCode >= 0) + { return null; + } + + return GetExceptionForHRInternal(errorCode, IntPtr.Zero); } public static Exception GetExceptionForHR(int errorCode, IntPtr errorInfo) { - if (errorCode < 0) - return GetExceptionForHRInternal(errorCode, errorInfo); - else + if (errorCode >= 0) + { return null; + } + + return GetExceptionForHRInternal(errorCode, errorInfo); } - [MethodImplAttribute(MethodImplOptions.InternalCall)] + [MethodImpl(MethodImplOptions.InternalCall)] internal static extern Exception GetExceptionForHRInternal(int errorCode, IntPtr errorInfo); - - //==================================================================== - // Memory allocation and deallocation. - //==================================================================== public static IntPtr AllocHGlobal(IntPtr cb) { // For backwards compatibility on 32 bit platforms, ensure we pass values between @@ -1030,22 +934,19 @@ namespace System.Runtime.InteropServices #endif IntPtr pNewMem = Win32Native.LocalAlloc_NoSafeHandle(LMEM_FIXED, unchecked(numBytes)); - if (pNewMem == IntPtr.Zero) { throw new OutOfMemoryException(); } + return pNewMem; } - public static IntPtr AllocHGlobal(int cb) - { - return AllocHGlobal((IntPtr)cb); - } + public static IntPtr AllocHGlobal(int cb) => AllocHGlobal((IntPtr)cb); public static void FreeHGlobal(IntPtr hglobal) { - if (IsNotWin32Atom(hglobal)) + if (!IsWin32Atom(hglobal)) { if (IntPtr.Zero != Win32Native.LocalFree(hglobal)) { @@ -1061,40 +962,34 @@ namespace System.Runtime.InteropServices { throw new OutOfMemoryException(); } + return pNewMem; } - - - //==================================================================== - // String convertions. - //==================================================================== + public static unsafe IntPtr StringToHGlobalAnsi(string s) { if (s == null) { return IntPtr.Zero; } - else - { - int nb = (s.Length + 1) * SystemMaxDBCSCharSize; - // Overflow checking - if (nb < s.Length) - throw new ArgumentOutOfRangeException(nameof(s)); + int nb = (s.Length + 1) * SystemMaxDBCSCharSize; - UIntPtr len = new UIntPtr((uint)nb); - IntPtr hglobal = Win32Native.LocalAlloc_NoSafeHandle(LMEM_FIXED, len); + // Overflow checking + if (nb < s.Length) + { + throw new ArgumentOutOfRangeException(nameof(s)); + } - if (hglobal == IntPtr.Zero) - { - throw new OutOfMemoryException(); - } - else - { - s.ConvertToAnsi((byte*)hglobal, nb, false, false); - return hglobal; - } + UIntPtr len = new UIntPtr((uint)nb); + IntPtr hglobal = Win32Native.LocalAlloc_NoSafeHandle(LMEM_FIXED, len); + if (hglobal == IntPtr.Zero) + { + throw new OutOfMemoryException(); } + + s.ConvertToAnsi((byte*)hglobal, nb, false, false); + return hglobal; } public static unsafe IntPtr StringToHGlobalUni(string s) @@ -1103,30 +998,27 @@ namespace System.Runtime.InteropServices { return IntPtr.Zero; } - else - { - int nb = (s.Length + 1) * 2; - // Overflow checking - if (nb < s.Length) - throw new ArgumentOutOfRangeException(nameof(s)); + int nb = (s.Length + 1) * 2; - UIntPtr len = new UIntPtr((uint)nb); - IntPtr hglobal = Win32Native.LocalAlloc_NoSafeHandle(LMEM_FIXED, len); + // Overflow checking + if (nb < s.Length) + { + throw new ArgumentOutOfRangeException(nameof(s)); + } - if (hglobal == IntPtr.Zero) - { - throw new OutOfMemoryException(); - } - else - { - fixed (char* firstChar = s) - { - string.wstrcpy((char*)hglobal, firstChar, s.Length + 1); - } - return hglobal; - } + UIntPtr len = new UIntPtr((uint)nb); + IntPtr hglobal = Win32Native.LocalAlloc_NoSafeHandle(LMEM_FIXED, len); + if (hglobal == IntPtr.Zero) + { + throw new OutOfMemoryException(); } + + fixed (char* firstChar = s) + { + string.wstrcpy((char*)hglobal, firstChar, s.Length + 1); + } + return hglobal; } public static IntPtr StringToHGlobalAuto(string s) @@ -1136,136 +1028,108 @@ namespace System.Runtime.InteropServices } #if FEATURE_COMINTEROP - - //==================================================================== - // Converts the CLR exception to an HRESULT. This function also sets - // up an IErrorInfo for the exception. - //==================================================================== - [MethodImplAttribute(MethodImplOptions.InternalCall)] + /// + /// Converts the CLR exception to an HRESULT. This function also sets + /// up an IErrorInfo for the exception. + /// + [MethodImpl(MethodImplOptions.InternalCall)] public static extern int GetHRForException(Exception e); - //==================================================================== - // Converts the CLR exception to an HRESULT. This function also sets - // up an IErrorInfo for the exception. - // This function is only used in WinRT and converts ObjectDisposedException - // to RO_E_CLOSED - //==================================================================== - [MethodImplAttribute(MethodImplOptions.InternalCall)] + /// + /// Converts the CLR exception to an HRESULT. This function also sets + /// up an IErrorInfo for the exception. + /// This function is only used in WinRT and converts ObjectDisposedException + /// to RO_E_CLOSED + /// + [MethodImpl(MethodImplOptions.InternalCall)] internal static extern int GetHRForException_WinRT(Exception e); - internal static readonly Guid ManagedNameGuid = new Guid("{0F21F359-AB84-41E8-9A78-36D110E6D2F9}"); - - //==================================================================== - // Given a managed object that wraps an ITypeInfo, return its name - //==================================================================== + /// + /// Given a managed object that wraps an ITypeInfo, return its name. + /// public static string GetTypeInfoName(ITypeInfo typeInfo) { if (typeInfo == null) + { throw new ArgumentNullException(nameof(typeInfo)); + } - string strTypeLibName = null; - string strDocString = null; - int dwHelpContext = 0; - string strHelpFile = null; - - typeInfo.GetDocumentation(-1, out strTypeLibName, out strDocString, out dwHelpContext, out strHelpFile); - + typeInfo.GetDocumentation(-1, out string strTypeLibName, out _, out _, out _); return strTypeLibName; } // This method is identical to Type.GetTypeFromCLSID. Since it's interop specific, we expose it // on Marshal for more consistent API surface. - public static Type GetTypeFromCLSID(Guid clsid) - { - return RuntimeType.GetTypeFromCLSIDImpl(clsid, null, false); - } + public static Type GetTypeFromCLSID(Guid clsid) => RuntimeType.GetTypeFromCLSIDImpl(clsid, null, throwOnError: false); - //==================================================================== - // return the IUnknown* for an Object if the current context - // is the one where the RCW was first seen. Will return null - // otherwise. - //==================================================================== + /// + /// Return the IUnknown* for an Object if the current context is the one + /// where the RCW was first seen. Will return null otherwise. + /// public static IntPtr /* IUnknown* */ GetIUnknownForObject(object o) { return GetIUnknownForObjectNative(o, false); } - [MethodImplAttribute(MethodImplOptions.InternalCall)] + [MethodImpl(MethodImplOptions.InternalCall)] private static extern IntPtr /* IUnknown* */ GetIUnknownForObjectNative(object o, bool onlyInContext); - //==================================================================== - // return the raw IUnknown* for a COM Object not related to current - // context - // Does not call AddRef - //==================================================================== - [MethodImplAttribute(MethodImplOptions.InternalCall)] + /// + /// Return the raw IUnknown* for a COM Object not related to current. + /// Does not call AddRef. + /// + [MethodImpl(MethodImplOptions.InternalCall)] internal static extern IntPtr /* IUnknown* */ GetRawIUnknownForComObjectNoAddRef(object o); #endif // FEATURE_COMINTEROP - //==================================================================== - // return the IDispatch* for an Object - //==================================================================== - public static IntPtr /* IDispatch */ GetIDispatchForObject(object o) - { - throw new PlatformNotSupportedException(); - } + public static IntPtr /* IDispatch */ GetIDispatchForObject(object o) => throw new PlatformNotSupportedException(); #if FEATURE_COMINTEROP - - //==================================================================== - // return the IUnknown* representing the interface for the Object - // Object o should support Type T - //==================================================================== + /// + /// Return the IUnknown* representing the interface for the Object. + /// Object o should support Type T + /// public static IntPtr /* IUnknown* */ GetComInterfaceForObject(object o, Type T) { return GetComInterfaceForObjectNative(o, T, false, true); } - public static IntPtr GetComInterfaceForObject(T o) - { - return GetComInterfaceForObject(o, typeof(TInterface)); - } + public static IntPtr GetComInterfaceForObject(T o) => GetComInterfaceForObject(o, typeof(TInterface)); - //==================================================================== - // return the IUnknown* representing the interface for the Object - // Object o should support Type T, it refer the value of mode to - // invoke customized QueryInterface or not - //==================================================================== + /// + /// Return the IUnknown* representing the interface for the Object. + /// Object o should support Type T, it refer the value of mode to + /// invoke customized QueryInterface or not. + /// public static IntPtr /* IUnknown* */ GetComInterfaceForObject(object o, Type T, CustomQueryInterfaceMode mode) { bool bEnableCustomizedQueryInterface = ((mode == CustomQueryInterfaceMode.Allow) ? true : false); return GetComInterfaceForObjectNative(o, T, false, bEnableCustomizedQueryInterface); } - [MethodImplAttribute(MethodImplOptions.InternalCall)] + [MethodImpl(MethodImplOptions.InternalCall)] private static extern IntPtr /* IUnknown* */ GetComInterfaceForObjectNative(object o, Type t, bool onlyInContext, bool fEnalbeCustomizedQueryInterface); - //==================================================================== - // return an Object for IUnknown - //==================================================================== - [MethodImplAttribute(MethodImplOptions.InternalCall)] + [MethodImpl(MethodImplOptions.InternalCall)] public static extern object GetObjectForIUnknown(IntPtr /* IUnknown* */ pUnk); - //==================================================================== - // Return a unique Object given an IUnknown. This ensures that you - // receive a fresh object (we will not look in the cache to match up this - // IUnknown to an already existing object). This is useful in cases - // where you want to be able to call ReleaseComObject on a RCW - // and not worry about other active uses of said RCW. - //==================================================================== - [MethodImplAttribute(MethodImplOptions.InternalCall)] + /// + /// Return a unique Object given an IUnknown. This ensures that you receive a fresh + /// object (we will not look in the cache to match up this IUnknown to an already + /// existing object). This is useful in cases where you want to be able to call + /// ReleaseComObject on a RCW and not worry about other active uses ofsaid RCW. + /// + [MethodImpl(MethodImplOptions.InternalCall)] public static extern object GetUniqueObjectForIUnknown(IntPtr unknown); - //==================================================================== - // return an Object for IUnknown, using the Type T, - // NOTE: - // Type T should be either a COM imported Type or a sub-type of COM - // imported Type - //==================================================================== - [MethodImplAttribute(MethodImplOptions.InternalCall)] + /// + /// Return an Object for IUnknown, using the Type T. + /// Type T should be either a COM imported Type or a sub-type of COM imported Type + /// + [MethodImpl(MethodImplOptions.InternalCall)] public static extern object GetTypedObjectForIUnknown(IntPtr /* IUnknown* */ pUnk, Type t); - [MethodImplAttribute(MethodImplOptions.InternalCall)] + [MethodImpl(MethodImplOptions.InternalCall)] public static extern IntPtr CreateAggregatedObject(IntPtr pOuter, object o); public static IntPtr CreateAggregatedObject(IntPtr pOuter, T o) @@ -1273,16 +1137,16 @@ namespace System.Runtime.InteropServices return CreateAggregatedObject(pOuter, (object)o); } - [MethodImplAttribute(MethodImplOptions.InternalCall)] + [MethodImpl(MethodImplOptions.InternalCall)] public static extern void CleanupUnusedObjectsInCurrentContext(); - [MethodImplAttribute(MethodImplOptions.InternalCall)] + [MethodImpl(MethodImplOptions.InternalCall)] public static extern bool AreComObjectsAvailableForCleanup(); - //==================================================================== - // check if the object is classic COM component - //==================================================================== - [MethodImplAttribute(MethodImplOptions.InternalCall)] + /// + /// Checks if the object is classic COM component. + /// + [MethodImpl(MethodImplOptions.InternalCall)] public static extern bool IsComObject(object o); #endif // FEATURE_COMINTEROP @@ -1294,6 +1158,7 @@ namespace System.Runtime.InteropServices { throw new OutOfMemoryException(); } + return pNewMem; } @@ -1303,29 +1168,26 @@ namespace System.Runtime.InteropServices { return IntPtr.Zero; } - else - { - int nb = (s.Length + 1) * 2; - // Overflow checking - if (nb < s.Length) - throw new ArgumentOutOfRangeException(nameof(s)); + int nb = (s.Length + 1) * 2; + + // Overflow checking + if (nb < s.Length) + { + throw new ArgumentOutOfRangeException(nameof(s)); + } - IntPtr hglobal = Win32Native.CoTaskMemAlloc(new UIntPtr((uint)nb)); + IntPtr hglobal = Win32Native.CoTaskMemAlloc(new UIntPtr((uint)nb)); + if (hglobal == IntPtr.Zero) + { + throw new OutOfMemoryException(); + } - if (hglobal == IntPtr.Zero) - { - throw new OutOfMemoryException(); - } - else - { - fixed (char* firstChar = s) - { - string.wstrcpy((char*)hglobal, firstChar, s.Length + 1); - } - return hglobal; - } + fixed (char* firstChar = s) + { + string.wstrcpy((char*)hglobal, firstChar, s.Length + 1); } + return hglobal; } public static unsafe IntPtr StringToCoTaskMemUTF8(string s) @@ -1334,27 +1196,21 @@ namespace System.Runtime.InteropServices { return IntPtr.Zero; } - else - { - int nb = Encoding.UTF8.GetMaxByteCount(s.Length); - IntPtr pMem = Win32Native.CoTaskMemAlloc(new UIntPtr((uint)nb + 1)); + int nb = Encoding.UTF8.GetMaxByteCount(s.Length); + IntPtr pMem = Win32Native.CoTaskMemAlloc(new UIntPtr((uint)nb + 1)); + if (pMem == IntPtr.Zero) + { + throw new OutOfMemoryException(); + } - if (pMem == IntPtr.Zero) - { - throw new OutOfMemoryException(); - } - else - { - fixed (char* firstChar = s) - { - byte* pbMem = (byte*)pMem; - int nbWritten = Encoding.UTF8.GetBytes(firstChar, s.Length, pbMem, nb); - pbMem[nbWritten] = 0; - } - return pMem; - } + fixed (char* firstChar = s) + { + byte* pbMem = (byte*)pMem; + int nbWritten = Encoding.UTF8.GetBytes(firstChar, s.Length, pbMem, nb); + pbMem[nbWritten] = 0; } + return pMem; } public static IntPtr StringToCoTaskMemAuto(string s) @@ -1369,31 +1225,28 @@ namespace System.Runtime.InteropServices { return IntPtr.Zero; } - else - { - int nb = (s.Length + 1) * SystemMaxDBCSCharSize; - // Overflow checking - if (nb < s.Length) - throw new ArgumentOutOfRangeException(nameof(s)); + int nb = (s.Length + 1) * SystemMaxDBCSCharSize; - IntPtr hglobal = Win32Native.CoTaskMemAlloc(new UIntPtr((uint)nb)); + // Overflow checking + if (nb < s.Length) + { + throw new ArgumentOutOfRangeException(nameof(s)); + } - if (hglobal == IntPtr.Zero) - { - throw new OutOfMemoryException(); - } - else - { - s.ConvertToAnsi((byte*)hglobal, nb, false, false); - return hglobal; - } + IntPtr hglobal = Win32Native.CoTaskMemAlloc(new UIntPtr((uint)nb)); + if (hglobal == IntPtr.Zero) + { + throw new OutOfMemoryException(); } + + s.ConvertToAnsi((byte*)hglobal, nb, false, false); + return hglobal; } public static void FreeCoTaskMem(IntPtr ptr) { - if (IsNotWin32Atom(ptr)) + if (!IsWin32Atom(ptr)) { Win32Native.CoTaskMemFree(ptr); } @@ -1406,15 +1259,13 @@ namespace System.Runtime.InteropServices { throw new OutOfMemoryException(); } + return pNewMem; } - //==================================================================== - // BSTR allocation and dealocation. - //==================================================================== public static void FreeBSTR(IntPtr ptr) { - if (IsNotWin32Atom(ptr)) + if (!IsWin32Atom(ptr)) { Win32Native.SysFreeString(ptr); } @@ -1423,15 +1274,21 @@ namespace System.Runtime.InteropServices public static IntPtr StringToBSTR(string s) { if (s == null) + { return IntPtr.Zero; + } // Overflow checking if (s.Length + 1 < s.Length) + { throw new ArgumentOutOfRangeException(nameof(s)); + } IntPtr bstr = Win32Native.SysAllocStringLen(s, s.Length); if (bstr == IntPtr.Zero) + { throw new OutOfMemoryException(); + } return bstr; } @@ -1442,20 +1299,13 @@ namespace System.Runtime.InteropServices } #if FEATURE_COMINTEROP - //==================================================================== - // release the COM component and if the reference hits 0 zombie this object - // further usage of this Object might throw an exception - //==================================================================== + /// + /// Release the COM component and if the reference hits 0 zombie this object. + /// Further usage of this Object might throw an exception + /// public static int ReleaseComObject(object o) { - __ComObject co = null; - - // Make sure the obj is an __ComObject. - try - { - co = (__ComObject)o; - } - catch (InvalidCastException) + if (!(o is __ComObject co)) { throw new ArgumentException(SR.Argument_ObjNotComObject, nameof(o)); } @@ -1463,90 +1313,125 @@ namespace System.Runtime.InteropServices return co.ReleaseSelf(); } - [MethodImplAttribute(MethodImplOptions.InternalCall)] + [MethodImpl(MethodImplOptions.InternalCall)] internal static extern int InternalReleaseComObject(object o); - - //==================================================================== - // release the COM component and zombie this object - // further usage of this Object might throw an exception - //==================================================================== + /// + /// Release the COM component and zombie this object. + /// Further usage of this Object might throw an exception + /// public static int FinalReleaseComObject(object o) { if (o == null) - throw new ArgumentNullException(nameof(o)); - - __ComObject co = null; - - // Make sure the obj is an __ComObject. - try { - co = (__ComObject)o; + throw new ArgumentNullException(nameof(o)); } - catch (InvalidCastException) + if (!(o is __ComObject co)) { throw new ArgumentException(SR.Argument_ObjNotComObject, nameof(o)); } co.FinalReleaseSelf(); - return 0; } - [MethodImplAttribute(MethodImplOptions.InternalCall)] + [MethodImpl(MethodImplOptions.InternalCall)] internal static extern void InternalFinalReleaseComObject(object o); -#endif // FEATURE_COMINTEROP - //==================================================================== - // This method retrieves data from the COM object. - //==================================================================== public static object GetComObjectData(object obj, object key) { - throw new PlatformNotSupportedException(SR.Arg_PlatformNotSupported); + if (obj == null) + { + throw new ArgumentNullException(nameof(obj)); + } + if (key == null) + { + throw new ArgumentNullException(nameof(key)); + } + if (!(obj is __ComObject co)) + { + throw new ArgumentException(SR.Argument_ObjNotComObject, nameof(obj)); + } + if (obj.GetType().IsWindowsRuntimeObject) + { + throw new ArgumentException(SR.Argument_ObjIsWinRTObject, nameof(obj)); + } + + // Retrieve the data from the __ComObject. + return co.GetData(key); } - //==================================================================== - // This method sets data on the COM object. The data can only be set - // once for a given key and cannot be removed. This function returns - // true if the data has been added, false if the data could not be - // added because there already was data for the specified key. - //==================================================================== + /// + /// Sets data on the COM object. The data can only be set once for a given key + /// and cannot be removed. This function returns true if the data has been added, + /// false if the data could not be added because there already was data for the + /// specified key. + /// public static bool SetComObjectData(object obj, object key, object data) { - throw new PlatformNotSupportedException(SR.Arg_PlatformNotSupported); + if (obj == null) + { + throw new ArgumentNullException(nameof(obj)); + } + if (key == null) + { + throw new ArgumentNullException(nameof(key)); + } + if (!(obj is __ComObject co)) + { + throw new ArgumentException(SR.Argument_ObjNotComObject, nameof(obj)); + } + if (obj.GetType().IsWindowsRuntimeObject) + { + throw new ArgumentException(SR.Argument_ObjIsWinRTObject, nameof(obj)); + } + + // Retrieve the data from the __ComObject. + return co.SetData(key, data); } -#if FEATURE_COMINTEROP - //==================================================================== - // This method takes the given COM object and wraps it in an object - // of the specified type. The type must be derived from __ComObject. - //==================================================================== + /// + /// This method takes the given COM object and wraps it in an object + /// of the specified type. The type must be derived from __ComObject. + /// public static object CreateWrapperOfType(object o, Type t) { - // Validate the arguments. if (t == null) + { throw new ArgumentNullException(nameof(t)); + } if (!t.IsCOMObject) + { throw new ArgumentException(SR.Argument_TypeNotComObject, nameof(t)); + } if (t.IsGenericType) + { throw new ArgumentException(SR.Argument_NeedNonGenericType, nameof(t)); - + } if (t.IsWindowsRuntimeObject) + { throw new ArgumentException(SR.Argument_TypeIsWinRTType, nameof(t)); + } - // Check for the null case. if (o == null) + { return null; + } - // Make sure the object is a COM object. if (!o.GetType().IsCOMObject) + { throw new ArgumentException(SR.Argument_ObjNotComObject, nameof(o)); + } if (o.GetType().IsWindowsRuntimeObject) + { throw new ArgumentException(SR.Argument_ObjIsWinRTObject, nameof(o)); + } - // Check to see if the type of the object is the requested type. + // Check to see if we have nothing to do. if (o.GetType() == t) + { return o; + } // Check to see if we already have a cached wrapper for this type. object Wrapper = GetComObjectData(o, t); @@ -1571,24 +1456,19 @@ namespace System.Runtime.InteropServices return (TWrapper)CreateWrapperOfType(o, typeof(TWrapper)); } - //==================================================================== - // Helper method called from CreateWrapperOfType. - //==================================================================== - [MethodImplAttribute(MethodImplOptions.InternalCall)] + [MethodImpl(MethodImplOptions.InternalCall)] private static extern object InternalCreateWrapperOfType(object o, Type t); - //==================================================================== - // IUnknown Helpers - //==================================================================== - [MethodImplAttribute(MethodImplOptions.InternalCall)] + [MethodImpl(MethodImplOptions.InternalCall)] public static extern int /* HRESULT */ QueryInterface(IntPtr /* IUnknown */ pUnk, ref Guid iid, out IntPtr ppv); - [MethodImplAttribute(MethodImplOptions.InternalCall)] + [MethodImpl(MethodImplOptions.InternalCall)] public static extern int /* ULONG */ AddRef(IntPtr /* IUnknown */ pUnk); - [MethodImplAttribute(MethodImplOptions.InternalCall)] + + [MethodImpl(MethodImplOptions.InternalCall)] public static extern int /* ULONG */ Release(IntPtr /* IUnknown */ pUnk); - [MethodImplAttribute(MethodImplOptions.InternalCall)] + [MethodImpl(MethodImplOptions.InternalCall)] public static extern void GetNativeVariantForObject(object obj, /* VARIANT * */ IntPtr pDstNativeVariant); public static void GetNativeVariantForObject(T obj, IntPtr pDstNativeVariant) @@ -1596,7 +1476,7 @@ namespace System.Runtime.InteropServices GetNativeVariantForObject((object)obj, pDstNativeVariant); } - [MethodImplAttribute(MethodImplOptions.InternalCall)] + [MethodImpl(MethodImplOptions.InternalCall)] public static extern object GetObjectForNativeVariant(/* VARIANT * */ IntPtr pSrcNativeVariant); public static T GetObjectForNativeVariant(IntPtr pSrcNativeVariant) @@ -1604,7 +1484,7 @@ namespace System.Runtime.InteropServices return (T)GetObjectForNativeVariant(pSrcNativeVariant); } - [MethodImplAttribute(MethodImplOptions.InternalCall)] + [MethodImpl(MethodImplOptions.InternalCall)] public static extern object[] GetObjectsForNativeVariants(/* VARIANT * */ IntPtr aSrcNativeVariant, int cVars); public static T[] GetObjectsForNativeVariants(IntPtr aSrcNativeVariant, int cVars) @@ -1625,36 +1505,36 @@ namespace System.Runtime.InteropServices /// Returns the first valid COM slot that GetMethodInfoForSlot will work on /// This will be 3 for IUnknown based interfaces and 7 for IDispatch based interfaces. /// - [MethodImplAttribute(MethodImplOptions.InternalCall)] + [MethodImpl(MethodImplOptions.InternalCall)] public static extern int GetStartComSlot(Type t); - #endif // FEATURE_COMINTEROP - //==================================================================== - // This method generates a GUID for the specified type. If the type - // has a GUID in the metadata then it is returned otherwise a stable - // guid GUID is generated based on the fully qualified name of the - // type. - //==================================================================== - public static Guid GenerateGuidForType(Type type) - { - return type.GUID; - } + /// + /// 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. + /// + public static Guid GenerateGuidForType(Type type) => type.GUID; - //==================================================================== - // 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. - //==================================================================== + /// + /// 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. + /// public static string GenerateProgIdForType(Type type) { if (type == 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)); + } IList cas = CustomAttributeData.GetCustomAttributes(type); for (int i = 0; i < cas.Count; i++) @@ -1682,20 +1562,13 @@ namespace System.Runtime.InteropServices } #if FEATURE_COMINTEROP - //==================================================================== - // This method binds to the specified moniker. - //==================================================================== public static object BindToMoniker(string monikerName) { - object obj = null; - IBindCtx bindctx = null; - CreateBindCtx(0, out bindctx); + CreateBindCtx(0, out IBindCtx bindctx); - uint cbEaten; - IMoniker pmoniker = null; - MkParseDisplayName(bindctx, monikerName, out cbEaten, out pmoniker); + MkParseDisplayName(bindctx, monikerName, out _, out IMoniker pmoniker); + BindMoniker(pmoniker, 0, ref IID_IUnknown, out object obj); - BindMoniker(pmoniker, 0, ref IID_IUnknown, out obj); return obj; } @@ -1708,52 +1581,58 @@ namespace System.Runtime.InteropServices [DllImport(Interop.Libraries.Ole32, PreserveSig = false)] private static extern void BindMoniker(IMoniker pmk, uint grfOpt, ref Guid iidResult, [MarshalAs(UnmanagedType.Interface)] out object ppvResult); - //======================================================================== - // Private method called from EE upon use of license/ICF2 marshaling. - //======================================================================== + /// + /// Private method called from EE upon use of license/ICF2 marshaling. + /// private static IntPtr LoadLicenseManager() { Type t = Type.GetType("System.ComponentModel.LicenseManager, System", throwOnError: true); return t.TypeHandle.Value; } - [MethodImplAttribute(MethodImplOptions.InternalCall)] + [MethodImpl(MethodImplOptions.InternalCall)] public static extern void ChangeWrapperHandleStrength(object otp, bool fIsWeak); - [MethodImplAttribute(MethodImplOptions.InternalCall)] + [MethodImpl(MethodImplOptions.InternalCall)] internal static extern void InitializeWrapperForWinRT(object o, ref IntPtr pUnk); #if FEATURE_COMINTEROP_WINRT_MANAGED_ACTIVATION - [MethodImplAttribute(MethodImplOptions.InternalCall)] + [MethodImpl(MethodImplOptions.InternalCall)] internal static extern void InitializeManagedWinRTFactoryObject(object o, RuntimeType runtimeClassType); #endif - //======================================================================== - // Create activation factory and wraps it with a unique RCW - //======================================================================== - [MethodImplAttribute(MethodImplOptions.InternalCall)] + /// + /// Create activation factory and wraps it with a unique RCW. + /// + [MethodImpl(MethodImplOptions.InternalCall)] internal static extern object GetNativeActivationFactory(Type type); #endif // FEATURE_COMINTEROP public static Delegate GetDelegateForFunctionPointer(IntPtr ptr, Type t) { - // Validate the parameters if (ptr == IntPtr.Zero) + { throw new ArgumentNullException(nameof(ptr)); - + } if (t == null) + { throw new ArgumentNullException(nameof(t)); - - if ((t as RuntimeType) == null) + } + if (!(t is RuntimeType)) + { throw new ArgumentException(SR.Argument_MustBeRuntimeType, nameof(t)); - + } if (t.IsGenericType) + { throw new ArgumentException(SR.Argument_NeedNonGenericType, nameof(t)); + } Type c = t.BaseType; if (c == null || (c != typeof(Delegate) && c != typeof(MulticastDelegate))) + { throw new ArgumentException(SR.Arg_MustBeDelegate, nameof(t)); + } return GetDelegateForFunctionPointerInternal(ptr, t); } @@ -1763,13 +1642,15 @@ namespace System.Runtime.InteropServices return (TDelegate)(object)GetDelegateForFunctionPointer(ptr, typeof(TDelegate)); } - [MethodImplAttribute(MethodImplOptions.InternalCall)] + [MethodImpl(MethodImplOptions.InternalCall)] internal static extern Delegate GetDelegateForFunctionPointerInternal(IntPtr ptr, Type t); public static IntPtr GetFunctionPointerForDelegate(Delegate d) { if (d == null) + { throw new ArgumentNullException(nameof(d)); + } return GetFunctionPointerForDelegateInternal(d); } @@ -1779,7 +1660,7 @@ namespace System.Runtime.InteropServices return GetFunctionPointerForDelegate((Delegate)(object)d); } - [MethodImplAttribute(MethodImplOptions.InternalCall)] + [MethodImpl(MethodImplOptions.InternalCall)] internal static extern IntPtr GetFunctionPointerForDelegateInternal(Delegate d); public static IntPtr SecureStringToBSTR(SecureString s) @@ -1869,4 +1750,3 @@ namespace System.Runtime.InteropServices } } } - diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/NativeCallableAttribute.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/NativeCallableAttribute.cs index d0ab0d9..ae38c17 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/NativeCallableAttribute.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/NativeCallableAttribute.cs @@ -2,26 +2,29 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -/*============================================================================= -** Any method marked with NativeCallableAttribute can be directly called from -** native code.The function token can be loaded to a local variable using LDFTN and -** passed as a callback to native method. -=============================================================================*/ - -using System; -using System.Runtime.CompilerServices; - namespace System.Runtime.InteropServices { + /// + /// Any method marked with NativeCallableAttribute can be directly called from + /// native code. The function token can be loaded to a local variable using LDFTN + /// and passed as a callback to native method. + /// [AttributeUsage(AttributeTargets.Method)] public sealed class NativeCallableAttribute : Attribute { public NativeCallableAttribute() { } - // Optional. If omitted , compiler will choose one for you. + + // + /// + /// Optional. If omitted , compiler will choose one for you. + /// public CallingConvention CallingConvention; - // Optional. If omitted, then the method is native callable, but no EAT is emitted. + + /// + /// Optional. If omitted, then the method is native callable, but no EAT is emitted. + /// public string EntryPoint; } } diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/NativeMethods.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/NativeMethods.cs index ccc8d20..bd7e9e5 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/NativeMethods.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/NativeMethods.cs @@ -2,25 +2,19 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. - -/*============================================================ -** -** -** Purpose: part of ComEventHelpers APIs which allow binding -** managed delegates to COM's connection point based events. -** -**/ #if FEATURE_COMINTEROP namespace System.Runtime.InteropServices { + /// + /// Part of ComEventHelpers APIs which allow binding managed delegates + /// to COM's connection point based events. + /// internal static class NativeMethods { - [ - ComImport, - InterfaceType(ComInterfaceType.InterfaceIsIUnknown), - Guid("00020400-0000-0000-C000-000000000046") - ] + [ComImport] + [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] + [Guid("00020400-0000-0000-C000-000000000046")] internal interface IDispatch { } diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/NonPortable.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/NonPortable.cs index 59229ed..c340376 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/NonPortable.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/NonPortable.cs @@ -4,26 +4,26 @@ // Dummy implementations of non-portable interop methods that just throw PlatformNotSupportedException +using System.Reflection; +using System.Runtime.InteropServices.ComTypes; + namespace System.Runtime.InteropServices { - public static partial class Marshal + public static partial class Marshal { public static int GetHRForException(Exception e) { return (e != null) ? e.HResult : 0; } - public static int AddRef(System.IntPtr pUnk) + public static int AddRef(IntPtr pUnk) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop); } - public static bool AreComObjectsAvailableForCleanup() - { - return false; - } + public static bool AreComObjectsAvailableForCleanup() => false; - public static System.IntPtr CreateAggregatedObject(System.IntPtr pOuter, object o) + public static IntPtr CreateAggregatedObject(IntPtr pOuter, object o) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop); } @@ -32,18 +32,18 @@ namespace System.Runtime.InteropServices { throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop); } - + public static void CleanupUnusedObjectsInCurrentContext() { - return; + return; } - public static System.IntPtr CreateAggregatedObject(System.IntPtr pOuter, T o) + public static IntPtr CreateAggregatedObject(IntPtr pOuter, T o) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop); } - public static object CreateWrapperOfType(object o, System.Type t) + public static object CreateWrapperOfType(object o, Type t) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop); } @@ -56,98 +56,104 @@ namespace System.Runtime.InteropServices public static void ChangeWrapperHandleStrength(Object otp, bool fIsWeak) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop); - } + } public static int FinalReleaseComObject(object o) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop); } - public static System.IntPtr GetComInterfaceForObject(object o, System.Type T) + public static IntPtr GetComInterfaceForObject(object o, Type T) + { + throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop); + } + + public static IntPtr GetComInterfaceForObject(object o, Type T, CustomQueryInterfaceMode mode) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop); } - public static System.IntPtr GetComInterfaceForObject(object o, System.Type T, System.Runtime.InteropServices.CustomQueryInterfaceMode mode) + public static IntPtr GetComInterfaceForObject(T o) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop); } - public static System.IntPtr GetComInterfaceForObject(T o) + public static object GetComObjectData(object obj, object key) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop); } - public static System.IntPtr GetHINSTANCE(System.Reflection.Module m) + public static IntPtr GetHINSTANCE(Module m) { if (m == null) { throw new ArgumentNullException(nameof(m)); } - return (System.IntPtr) (-1); + + return (IntPtr) (-1); } - public static System.IntPtr GetIUnknownForObject(object o) + public static IntPtr GetIUnknownForObject(object o) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop); } - public static void GetNativeVariantForObject(object obj, System.IntPtr pDstNativeVariant) + public static void GetNativeVariantForObject(object obj, IntPtr pDstNativeVariant) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop); } - public static void GetNativeVariantForObject(T obj, System.IntPtr pDstNativeVariant) + public static void GetNativeVariantForObject(T obj, IntPtr pDstNativeVariant) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop); } - public static Object GetTypedObjectForIUnknown(System.IntPtr pUnk, System.Type t) + public static Object GetTypedObjectForIUnknown(IntPtr pUnk, Type t) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop); } - public static object GetObjectForIUnknown(System.IntPtr pUnk) + public static object GetObjectForIUnknown(IntPtr pUnk) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop); } - public static object GetObjectForNativeVariant(System.IntPtr pSrcNativeVariant) + public static object GetObjectForNativeVariant(IntPtr pSrcNativeVariant) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop); } - public static T GetObjectForNativeVariant(System.IntPtr pSrcNativeVariant) + public static T GetObjectForNativeVariant(IntPtr pSrcNativeVariant) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop); } - public static object[] GetObjectsForNativeVariants(System.IntPtr aSrcNativeVariant, int cVars) + public static object[] GetObjectsForNativeVariants(IntPtr aSrcNativeVariant, int cVars) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop); } - public static T[] GetObjectsForNativeVariants(System.IntPtr aSrcNativeVariant, int cVars) + public static T[] GetObjectsForNativeVariants(IntPtr aSrcNativeVariant, int cVars) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop); } - public static int GetStartComSlot(System.Type t) + public static int GetStartComSlot(Type t) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop); } - public static System.Type GetTypeFromCLSID(System.Guid clsid) + public static Type GetTypeFromCLSID(Guid clsid) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop); } - public static string GetTypeInfoName(System.Runtime.InteropServices.ComTypes.ITypeInfo typeInfo) + public static string GetTypeInfoName(ITypeInfo typeInfo) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop); } - public static object GetUniqueObjectForIUnknown(System.IntPtr unknown) + public static object GetUniqueObjectForIUnknown(IntPtr unknown) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop); } @@ -162,12 +168,12 @@ namespace System.Runtime.InteropServices return false; } - public static int QueryInterface(System.IntPtr pUnk, ref System.Guid iid, out System.IntPtr ppv) + public static int QueryInterface(IntPtr pUnk, ref Guid iid, out IntPtr ppv) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop); } - public static int Release(System.IntPtr pUnk) + public static int Release(IntPtr pUnk) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop); } @@ -176,6 +182,11 @@ namespace System.Runtime.InteropServices { throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop); } + + public static bool SetComObjectData(object obj, object key, object data) + { + throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop); + } } public class DispatchWrapper @@ -185,26 +196,19 @@ namespace System.Runtime.InteropServices throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop); } - public object WrappedObject - { - get - { - throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop); - } - } + public object WrappedObject => throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop); } public static class ComEventsHelper { - public static void Combine(object rcw, System.Guid iid, int dispid, System.Delegate d) + public static void Combine(object rcw, Guid iid, int dispid, Delegate d) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop); } - public static System.Delegate Remove(object rcw, System.Guid iid, int dispid, System.Delegate d) + public static Delegate Remove(object rcw, Guid iid, int dispid, Delegate d) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop); } } } - diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/PInvokeMap.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/PInvokeMap.cs index 33f1b5f..c0db011 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/PInvokeMap.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/PInvokeMap.cs @@ -2,20 +2,12 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -//////////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////////// -// -// PInvokeMap is an enum that defines the PInvoke attributes. These -// values are defined in CorHdr.h. -// -// - -using System.Runtime.InteropServices; -using System; - namespace System.Runtime.InteropServices { - // This Enum matchs the CorPinvokeMap defined in CorHdr.h + /// + /// An enum that defines the PInvoke attributes. These values + /// values are defined in and must match CorHdr.h. + /// internal enum PInvokeMap { NoMangle = 0x0001, // Pinvoke is to use the member name as specified. diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/SEHException.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/SEHException.cs index e933baa..846ea4e 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/SEHException.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/SEHException.cs @@ -11,15 +11,16 @@ ** =============================================================================*/ -using System.Runtime.InteropServices; -using System; +using System.Runtime.CompilerServices; using System.Runtime.Serialization; namespace System.Runtime.InteropServices { - // Exception for Structured Exception Handler exceptions. + /// + /// Exception for Structured Exception Handler exceptions. + /// [Serializable] - [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] + [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class SEHException : ExternalException { public SEHException() @@ -52,9 +53,6 @@ namespace System.Runtime.InteropServices // Resumable exceptions aren't implemented in this version, // but this method exists and always returns false. // - public virtual bool CanResume() - { - return false; - } + public virtual bool CanResume() => false; } } diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/SafeArrayRankMismatchException.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/SafeArrayRankMismatchException.cs index 28154e9..661810c 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/SafeArrayRankMismatchException.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/SafeArrayRankMismatchException.cs @@ -2,22 +2,17 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -/*============================================================================= -** -** -** Purpose: This exception is thrown when the runtime rank of a safe array -** is different than the array rank specified in the metadata. -** -=============================================================================*/ - - -using System; +using System.Runtime.CompilerServices; using System.Runtime.Serialization; namespace System.Runtime.InteropServices { + /// + /// The exception is thrown when the runtime rank of a safe array is different + /// than the array rank specified in the metadata. + /// [Serializable] - [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] + [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class SafeArrayRankMismatchException : SystemException { public SafeArrayRankMismatchException() diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/SafeArrayTypeMismatchException.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/SafeArrayTypeMismatchException.cs index 4118628..c094ec1 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/SafeArrayTypeMismatchException.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/SafeArrayTypeMismatchException.cs @@ -2,23 +2,17 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -/*============================================================================= -** -** -** Purpose: This exception is thrown when the runtime type of an array -** is different than the safe array sub type specified in the -** metadata. -** -=============================================================================*/ - - -using System; +using System.Runtime.CompilerServices; using System.Runtime.Serialization; namespace System.Runtime.InteropServices { + /// + /// The exception is thrown when the runtime type of an array is different + /// than the safe array sub type specified in the metadata. + /// [Serializable] - [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] + [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class SafeArrayTypeMismatchException : SystemException { public SafeArrayTypeMismatchException() diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/UnknownWrapper.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/UnknownWrapper.cs index dc57bb4..4f5a6b3 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/UnknownWrapper.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/UnknownWrapper.cs @@ -2,20 +2,11 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -/*============================================================================= -** -** -** -** Purpose: Wrapper that is converted to a variant with VT_UNKNOWN. -** -** -=============================================================================*/ - - -using System; - namespace System.Runtime.InteropServices { + /// + /// Wrapper that is converted to a variant with VT_UNKNOWN. + /// public sealed class UnknownWrapper { public UnknownWrapper(object obj) @@ -23,13 +14,7 @@ namespace System.Runtime.InteropServices m_WrappedObject = obj; } - public object WrappedObject - { - get - { - return m_WrappedObject; - } - } + public object WrappedObject => m_WrappedObject; private object m_WrappedObject; } diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/VariantWrapper.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/VariantWrapper.cs index 3abf880..0266987 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/VariantWrapper.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/VariantWrapper.cs @@ -2,20 +2,11 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -/*============================================================================= -** -** -** -** Purpose: Wrapper that is converted to a variant with VT_BYREF | VT_VARIANT. -** -** -=============================================================================*/ - - -using System; - namespace System.Runtime.InteropServices { + /// + /// Wrapper that is converted to a variant with VT_BYREF | VT_VARIANT. + /// public sealed class VariantWrapper { public VariantWrapper(object obj) @@ -23,13 +14,7 @@ namespace System.Runtime.InteropServices m_WrappedObject = obj; } - public object WrappedObject - { - get - { - return m_WrappedObject; - } - } + public object WrappedObject => m_WrappedObject; private object m_WrappedObject; } diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/Attributes.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/Attributes.cs index 84854c9..b8376e4 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/Attributes.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/Attributes.cs @@ -2,8 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -// - using System; namespace System.Runtime.InteropServices.WindowsRuntime @@ -19,10 +17,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime m_defaultInterface = defaultInterface; } - public Type DefaultInterface - { - get { return m_defaultInterface; } - } + public Type DefaultInterface => m_defaultInterface; } // WindowsRuntimeImport is a pseudo custom attribute which causes us to emit the tdWindowsRuntime bit @@ -34,8 +29,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime [AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.Enum | AttributeTargets.Struct | AttributeTargets.Delegate, Inherited = false)] internal sealed class WindowsRuntimeImportAttribute : Attribute { - internal WindowsRuntimeImportAttribute() - { } + internal WindowsRuntimeImportAttribute() { } } // This attribute is applied to class interfaces in a generated projection assembly. It is used by Visual Studio @@ -53,30 +47,15 @@ namespace System.Runtime.InteropServices.WindowsRuntime m_revisionVersion = revisionVersion; } - public Type InterfaceType - { - get { return m_interfaceType; } - } + public Type InterfaceType => m_interfaceType; - public byte MajorVersion - { - get { return m_majorVersion; } - } + public byte MajorVersion => m_majorVersion; - public byte MinorVersion - { - get { return m_minorVersion; } - } + public byte MinorVersion => m_minorVersion; - public byte BuildVersion - { - get { return m_buildVersion; } - } + public byte BuildVersion => m_buildVersion; - public byte RevisionVersion - { - get { return m_revisionVersion; } - } + public byte RevisionVersion => m_revisionVersion; private Type m_interfaceType; private byte m_majorVersion; @@ -99,8 +78,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime public WriteOnlyArrayAttribute() { } } - - // This attribute is applied on the return value to specify the name of the return value. // In WindowsRuntime all parameters including return value need to have unique names. // This is essential in JS as one of the ways to get at the results of a method in JavaScript is via a Dictionary object keyed by parameter name. @@ -108,14 +85,12 @@ namespace System.Runtime.InteropServices.WindowsRuntime public sealed class ReturnValueNameAttribute : Attribute { private string m_Name; + public ReturnValueNameAttribute(string name) { m_Name = name; } - public string Name - { - get { return m_Name; } - } + public string Name => m_Name; } } diff --git a/src/System.Private.CoreLib/src/System/__ComObject.cs b/src/System.Private.CoreLib/src/System/__ComObject.cs index 8175637..509f7bb 100644 --- a/src/System.Private.CoreLib/src/System/__ComObject.cs +++ b/src/System.Private.CoreLib/src/System/__ComObject.cs @@ -2,55 +2,41 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -/*============================================================ -** -** -** -** __ComObject is the root class for all COM wrappers. This class -** defines only the basics. This class is used for wrapping COM objects -** accessed from COM+ -** -** -===========================================================*/ - -using System; using System.Collections; -using System.Threading; using System.Runtime.InteropServices; using System.Runtime.InteropServices.WindowsRuntime; -using System.Runtime.CompilerServices; using System.Reflection; namespace System { + /// + /// __ComObject is the root class for all COM wrappers. This class defines only + /// the basics. This class is used for wrapping COM objects accessed from managed. + /// internal class __ComObject : MarshalByRefObject { - private Hashtable m_ObjectToDataMap; + private Hashtable m_ObjectToDataMap; // Do not rename (runtime relies on this name). - /*============================================================ - ** default constructor - ** can't instantiate this directly - =============================================================*/ + /// + /// Default constructor - can't instantiate this directly. + /// protected __ComObject() { } - //==================================================================== - // Overrides ToString() to make sure we call to IStringable if the - // COM object implements it in the case of weakly typed RCWs - //==================================================================== + /// + /// Overrides ToString() to make sure we call to IStringable if the COM + /// object implements it in the case of weakly typed RCWs + /// public override string ToString() { - // // Only do the IStringable cast when running under AppX for better compat // Otherwise we could do a IStringable cast in classic apps which could introduce - // a thread transition which would lead to deadlock - // + // a thread transition which would lead to deadlock. if (AppDomain.IsAppXModel()) { // Check whether the type implements IStringable. - IStringable stringableType = this as IStringable; - if (stringableType != null) + if (this is IStringable stringableType) { return stringableType.ToString(); } @@ -59,10 +45,9 @@ namespace System return base.ToString(); } - //==================================================================== - // This method retrieves the data associated with the specified - // key if any such data exists for the current __ComObject. - //==================================================================== + /// + /// Retrieves the data associated with the specified if such data exists. + /// internal object GetData(object key) { object data = null; @@ -81,10 +66,9 @@ namespace System return data; } - //==================================================================== - // This method sets the data for the specified key on the current - // __ComObject. - //==================================================================== + /// + /// Sets the data for the specified key on the current __ComObject. + /// internal bool SetData(object key, object data) { bool bAdded = false; @@ -94,7 +78,9 @@ namespace System { // If the map hasn't been allocated yet, allocate it. if (m_ObjectToDataMap == null) + { m_ObjectToDataMap = new Hashtable(); + } // If there isn't already data in the map then add it. if (m_ObjectToDataMap[key] == null) @@ -107,10 +93,9 @@ namespace System return bAdded; } - //==================================================================== - // This method is called from within the EE and releases all the - // cached data for the __ComObject. - //==================================================================== + /// + /// Called from within the EE and releases all the cached data for the __ComObject. + /// internal void ReleaseAllData() { // Synchronize access to the map. @@ -125,13 +110,11 @@ namespace System // We are fine for now as object[] doesn't implement IDisposable nor derive from __ComObject // If the object implements IDisposable, then call Dispose on it. - IDisposable DisposableObj = o as IDisposable; - if (DisposableObj != null) + if (o is IDisposable DisposableObj) DisposableObj.Dispose(); // If the object is a derived from __ComObject, then call Marshal.ReleaseComObject on it. - __ComObject ComObj = o as __ComObject; - if (ComObj != null) + if (o is __ComObject ComObj) Marshal.ReleaseComObject(ComObj); } @@ -140,32 +123,26 @@ namespace System } } } - - //==================================================================== - // This method is called from within the EE and is used to handle - // calls on methods of event interfaces. - //==================================================================== + + /// + /// Called from within the EE and is used to handle calls on methods of event interfaces. + /// internal object GetEventProvider(RuntimeType t) { // Check to see if we already have a cached event provider for this type. - object EvProvider = GetData(t); + object provider = GetData(t); + if (provider != null) + { + return provider; + } // If we don't then we need to create one. - if (EvProvider == null) - EvProvider = CreateEventProvider(t); - - return EvProvider; + return CreateEventProvider(t); } - internal int ReleaseSelf() - { - return Marshal.InternalReleaseComObject(this); - } + internal int ReleaseSelf() => Marshal.InternalReleaseComObject(this); - internal void FinalReleaseSelf() - { - Marshal.InternalFinalReleaseComObject(this); - } + internal void FinalReleaseSelf() => Marshal.InternalFinalReleaseComObject(this); private object CreateEventProvider(RuntimeType t) { @@ -176,9 +153,10 @@ namespace System if (!SetData(t, EvProvider)) { // Dispose the event provider if it implements IDisposable. - IDisposable DisposableEvProv = EvProvider as IDisposable; - if (DisposableEvProv != null) + if (EvProvider is IDisposable DisposableEvProv) + { DisposableEvProv.Dispose(); + } // Another thead already cached the wrapper so use that one instead. EvProvider = GetData(t); diff --git a/tests/CoreFX/CoreFX.issues.json b/tests/CoreFX/CoreFX.issues.json index a9df7aa..3021d1d 100644 --- a/tests/CoreFX/CoreFX.issues.json +++ b/tests/CoreFX/CoreFX.issues.json @@ -217,6 +217,40 @@ } }, { + "name": "System.Runtime.InteropServices.Tests", + "enabled": true, + "exclusions": { + "namespaces": null, + "classes": null, + "methods": [ + { + "name": "System.Runtime.InteropServices.MarshalTests.SetComObjectData", + "reason": "outdated" + }, + { + "name": "System.Runtime.InteropServices.MarshalTests.GetComObjectData", + "reason": "outdated" + }, + { + "name": "System.Runtime.InteropServices.Tests.ComAwareEventInfoTests.AddEventHandler_DispIdAttribute_ThrowsPlatformNotSupportedException", + "reason": "outdated" + }, + { + "name": "System.Runtime.InteropServices.Tests.ComEventsHelperTests.Remove_NonNullRcw_ThrowsPlatformNotSupportedException", + "reason": "outdated" + }, + { + "name": "System.Runtime.InteropServices.Tests.ComEventsHelperTests.AddEventHandler_DispIdAttribute_ThrowsPlatformNotSupportedException", + "reason": "outdated" + }, + { + "name": "System.Runtime.InteropServices.Tests.ComEventsHelperTests.Combine_NonNullRcw_ThrowsPlatformNotSupportedException", + "reason": "outdated" + }, + ] + } + }, + { "name": "System.Security.Cryptography.X509Certificates.Tests", "enabled": true, "exclusions": { -- 2.7.4