<InteropSources Condition="'$(FeatureCoreClr)'=='true'" Include="$(BclSourcesRoot)\System\Runtime\InteropServices\NativeCallableAttribute.cs" />
<InteropSources Condition="'$(FeatureCominterop)' != 'true'" Include="$(BclSourcesRoot)\System\Runtime\InteropServices\NonPortable.cs" />
<InteropSources Condition="'$(FeatureCominterop)' == 'true'" Include="$(BclSourcesRoot)\System\Runtime\InteropServices\DispatchWrapper.cs" />
- <InteropSources Condition="'$(FeatureCominterop)' == 'true'" Include="$(BclSourcesRoot)\System\Runtime\InteropServices\ExtensibleClassFactory.cs" />
<InteropSources Include="$(BclSourcesRoot)\System\Runtime\InteropServices\ICustomFactory.cs" />
- <InteropSources Condition="'$(FeatureCominterop)' == 'true'" Include="$(BclSourcesRoot)\System\Runtime\InteropServices\ObjectCreationDelegate.cs" />
</ItemGroup>
<ItemGroup>
<InteropSources Include="$(CoreFxSourcesRoot)\System\Runtime\InteropServices\StringBuffer.cs" />
</ItemGroup>
<ItemGroup Condition="'$(FeatureClassicCominterop)' == 'true'">
- <InteropSources Include="$(BclSourcesRoot)\System\Runtime\InteropServices\IRegistrationServices.cs" />
<InteropSources Include="$(BclSourcesRoot)\System\Runtime\InteropServices\ITypeLibConverter.cs" />
- <InteropSources Include="$(BclSourcesRoot)\System\Runtime\InteropServices\RegistrationServices.cs" />
- <InteropSources Include="$(BclSourcesRoot)\System\Runtime\InteropServices\UCOMIBindCtx.cs" />
- <InteropSources Include="$(BclSourcesRoot)\System\Runtime\InteropServices\UCOMIConnectionPointContainer.cs" />
- <InteropSources Include="$(BclSourcesRoot)\System\Runtime\InteropServices\UCOMIConnectionPoint.cs" />
- <InteropSources Include="$(BclSourcesRoot)\System\Runtime\InteropServices\UCOMIEnumerable.cs" />
- <InteropSources Include="$(BclSourcesRoot)\System\Runtime\InteropServices\UCOMIEnumerator.cs" />
- <InteropSources Include="$(BclSourcesRoot)\System\Runtime\InteropServices\UCOMIEnumMoniker.cs" />
- <InteropSources Include="$(BclSourcesRoot)\System\Runtime\InteropServices\UCOMIEnumConnections.cs" />
- <InteropSources Include="$(BclSourcesRoot)\System\Runtime\InteropServices\UCOMIEnumConnectionPoints.cs" />
- <InteropSources Include="$(BclSourcesRoot)\System\Runtime\InteropServices\UCOMIEnumString.cs" />
- <InteropSources Include="$(BclSourcesRoot)\System\Runtime\InteropServices\UCOMIEnumVARIANT.cs" />
- <InteropSources Include="$(BclSourcesRoot)\System\Runtime\InteropServices\UCOMIExpando.cs" />
- <InteropSources Include="$(BclSourcesRoot)\System\Runtime\InteropServices\UCOMIMoniker.cs" />
- <InteropSources Include="$(BclSourcesRoot)\System\Runtime\InteropServices\UCOMIPersistFile.cs" />
- <InteropSources Include="$(BclSourcesRoot)\System\Runtime\InteropServices\UCOMIReflect.cs" />
- <InteropSources Include="$(BclSourcesRoot)\System\Runtime\InteropServices\UCOMIRunningObjectTable.cs" />
- <InteropSources Include="$(BclSourcesRoot)\System\Runtime\InteropServices\UCOMIStream.cs" />
- <InteropSources Include="$(BclSourcesRoot)\System\Runtime\InteropServices\UCOMITypeComp.cs" />
- <InteropSources Include="$(BclSourcesRoot)\System\Runtime\InteropServices\UCOMITypeInfo.cs" />
- <InteropSources Include="$(BclSourcesRoot)\System\Runtime\InteropServices\UCOMITypeLib.cs" />
</ItemGroup>
<ItemGroup>
<InteropExpandoSources Include="$(BclSourcesRoot)\System\Runtime\InteropServices\Expando\IExpando.cs" />
<InteropComeventsSources Include="$(BclSourcesRoot)\System\Runtime\InteropServices\ComEventsMethod.cs" />
<InteropComeventsSources Include="$(BclSourcesRoot)\System\Runtime\InteropServices\ComEventsSink.cs" />
<InteropComeventsSources Include="$(BclSourcesRoot)\System\Runtime\InteropServices\NativeMethods.cs" />
- <InteropComeventsSources Include="$(BclSourcesRoot)\System\Runtime\InteropServices\Variant.cs" />
</ItemGroup>
<ItemGroup>
<InteropComtypesSources Include="$(BclSourcesRoot)\System\Runtime\InteropServices\ComTypes\IBindCtx.cs" />
<InteropComtypesSources Include="$(BclSourcesRoot)\System\Runtime\InteropServices\ComTypes\IConnectionPointContainer.cs" />
<InteropComtypesSources Include="$(BclSourcesRoot)\System\Runtime\InteropServices\ComTypes\IConnectionPoint.cs" />
- <InteropComtypesSources Include="$(BclSourcesRoot)\System\Runtime\InteropServices\ComTypes\IEnumerable.cs" />
- <InteropComtypesSources Include="$(BclSourcesRoot)\System\Runtime\InteropServices\ComTypes\IEnumerator.cs" />
<InteropComtypesSources Include="$(BclSourcesRoot)\System\Runtime\InteropServices\ComTypes\IEnumMoniker.cs" />
<InteropComtypesSources Include="$(BclSourcesRoot)\System\Runtime\InteropServices\ComTypes\IEnumConnections.cs" />
<InteropComtypesSources Include="$(BclSourcesRoot)\System\Runtime\InteropServices\ComTypes\IEnumConnectionPoints.cs" />
<InteropComtypesSources Include="$(BclSourcesRoot)\System\Runtime\InteropServices\ComTypes\IEnumString.cs" />
<InteropComtypesSources Include="$(BclSourcesRoot)\System\Runtime\InteropServices\ComTypes\IEnumVARIANT.cs" />
- <InteropComtypesSources Include="$(BclSourcesRoot)\System\Runtime\InteropServices\ComTypes\IExpando.cs" />
<InteropComtypesSources Include="$(BclSourcesRoot)\System\Runtime\InteropServices\ComTypes\IMoniker.cs" />
<InteropComtypesSources Include="$(BclSourcesRoot)\System\Runtime\InteropServices\ComTypes\IPersistFile.cs" />
- <InteropComtypesSources Include="$(BclSourcesRoot)\System\Runtime\InteropServices\ComTypes\IReflect.cs" />
<InteropComtypesSources Include="$(BclSourcesRoot)\System\Runtime\InteropServices\ComTypes\IRunningObjectTable.cs" />
<InteropComtypesSources Include="$(BclSourcesRoot)\System\Runtime\InteropServices\ComTypes\IStream.cs" />
<InteropComtypesSources Include="$(BclSourcesRoot)\System\Runtime\InteropServices\ComTypes\ITypeComp.cs" />
<Win32Sources Condition="'$(FeatureWin32Registry)' == 'true'" Include="$(BclSourcesRoot)\Microsoft\Win32\RegistryView.cs" />
<Win32Sources Condition="'$(FeatureClassicCominterop)' == 'true'" Include="$(BclSourcesRoot)\Microsoft\Win32\OAVariantLib.cs" />
</ItemGroup>
- <ItemGroup Condition="'$(FeatureClassicCominterop)' == 'true'" >
- <InteropTceadaptergenSources Include="$(BclSourcesRoot)\System\Runtime\InteropServices\TCEAdapterGen\EventProviderWriter.cs" />
- <InteropTceadaptergenSources Include="$(BclSourcesRoot)\System\Runtime\InteropServices\TCEAdapterGen\EventSinkHelperWriter.cs" />
- <InteropTceadaptergenSources Include="$(BclSourcesRoot)\System\Runtime\InteropServices\TCEAdapterGen\EventItfInfo.cs" />
- <InteropTceadaptergenSources Include="$(BclSourcesRoot)\System\Runtime\InteropServices\TCEAdapterGen\NameSpaceExtractor.cs" />
- <InteropTceadaptergenSources Include="$(BclSourcesRoot)\System\Runtime\InteropServices\TCEAdapterGen\TCEAdapterGenerator.cs" />
- </ItemGroup>
<ItemGroup>
<SecurityPrincipalSources Include="$(BclSourcesRoot)\System\Security\Principal\IIdentity.cs" />
<SecurityPrincipalSources Include="$(BclSourcesRoot)\System\Security\Principal\IPrincipal.cs" />
<MscorlibSources Include="@(ConfigurationAssembliesSources)"/>
<MscorlibSources Include="@(SecCryptographySources)"/>
<MscorlibSources Include="@(SecPublickeySources)"/>
- <MscorlibSources Include="@(InteropTceadaptergenSources)"/>
<MscorlibSources Include="@(SecurityAclSources)"/>
<MscorlibSources Include="@(IdentitySources)"/>
<MscorlibSources Include="@(VersioningSources)"/>
}
}
-[Serializable]
-[Flags()]
- [System.Runtime.InteropServices.ComVisible(true)]
- public enum TypeLibTypeFlags
- {
- FAppObject = 0x0001,
- FCanCreate = 0x0002,
- FLicensed = 0x0004,
- FPreDeclId = 0x0008,
- FHidden = 0x0010,
- FControl = 0x0020,
- FDual = 0x0040,
- FNonExtensible = 0x0080,
- FOleAutomation = 0x0100,
- FRestricted = 0x0200,
- FAggregatable = 0x0400,
- FReplaceable = 0x0800,
- FDispatchable = 0x1000,
- FReverseBind = 0x2000,
- }
-
-[Serializable]
-[Flags()]
- [System.Runtime.InteropServices.ComVisible(true)]
- public enum TypeLibFuncFlags
- {
- FRestricted = 0x0001,
- FSource = 0x0002,
- FBindable = 0x0004,
- FRequestEdit = 0x0008,
- FDisplayBind = 0x0010,
- FDefaultBind = 0x0020,
- FHidden = 0x0040,
- FUsesGetLastError = 0x0080,
- FDefaultCollelem = 0x0100,
- FUiDefault = 0x0200,
- FNonBrowsable = 0x0400,
- FReplaceable = 0x0800,
- FImmediateBind = 0x1000,
- }
-
-[Serializable]
-[Flags()]
- [System.Runtime.InteropServices.ComVisible(true)]
- public enum TypeLibVarFlags
- {
- FReadOnly = 0x0001,
- FSource = 0x0002,
- FBindable = 0x0004,
- FRequestEdit = 0x0008,
- FDisplayBind = 0x0010,
- FDefaultBind = 0x0020,
- FHidden = 0x0040,
- FRestricted = 0x0080,
- FDefaultCollelem = 0x0100,
- FUiDefault = 0x0200,
- FNonBrowsable = 0x0400,
- FReplaceable = 0x0800,
- FImmediateBind = 0x1000,
- }
-
- [AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.Enum | AttributeTargets.Struct, Inherited = false)]
- [System.Runtime.InteropServices.ComVisible(true)]
- public sealed class TypeLibTypeAttribute : Attribute
- {
- internal TypeLibTypeFlags _val;
- public TypeLibTypeAttribute(TypeLibTypeFlags flags)
- {
- _val = flags;
- }
- public TypeLibTypeAttribute(short flags)
- {
- _val = (TypeLibTypeFlags)flags;
- }
- public TypeLibTypeFlags Value { get {return _val;} }
- }
-
- [AttributeUsage(AttributeTargets.Method, Inherited = false)]
- [System.Runtime.InteropServices.ComVisible(true)]
- public sealed class TypeLibFuncAttribute : Attribute
- {
- internal TypeLibFuncFlags _val;
- public TypeLibFuncAttribute(TypeLibFuncFlags flags)
- {
- _val = flags;
- }
- public TypeLibFuncAttribute(short flags)
- {
- _val = (TypeLibFuncFlags)flags;
- }
- public TypeLibFuncFlags Value { get {return _val;} }
- }
-
- [AttributeUsage(AttributeTargets.Field, Inherited = false)]
- [System.Runtime.InteropServices.ComVisible(true)]
- public sealed class TypeLibVarAttribute : Attribute
- {
- internal TypeLibVarFlags _val;
- public TypeLibVarAttribute(TypeLibVarFlags flags)
- {
- _val = flags;
- }
- public TypeLibVarAttribute(short flags)
- {
- _val = (TypeLibVarFlags)flags;
- }
- public TypeLibVarFlags Value { get {return _val;} }
- }
-
[Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public enum VarEnum
using System.Diagnostics;
// see code:ComEventsHelper#ComEventsArchitecture
- internal class ComEventsSink : NativeMethods.IDispatch, ICustomQueryInterface
+ internal class ComEventsSink : ICustomQueryInterface
{
#region private fields
#endregion
-
-#region IDispatch Members
-
- void NativeMethods.IDispatch.GetTypeInfoCount(out uint pctinfo) {
- pctinfo = 0;
- }
-
- void NativeMethods.IDispatch.GetTypeInfo(uint iTInfo, int lcid, out IntPtr info) {
- throw new NotImplementedException();
- }
-
- void NativeMethods.IDispatch.GetIDsOfNames(ref Guid iid, string[] names, uint cNames, int lcid, int[] rgDispId) {
- throw new NotImplementedException();
- }
-
- private const VarEnum VT_BYREF_VARIANT = VarEnum.VT_BYREF | VarEnum.VT_VARIANT;
- private const VarEnum VT_TYPEMASK = (VarEnum) 0x0fff;
- private const VarEnum VT_BYREF_TYPEMASK = VT_TYPEMASK | VarEnum.VT_BYREF;
-
- private static unsafe Variant *GetVariant(Variant *pSrc)
- {
- if (pSrc->VariantType == VT_BYREF_VARIANT)
- {
- // For VB6 compatibility reasons, if the VARIANT is a VT_BYREF | VT_VARIANT that
- // contains another VARIANT with VT_BYREF | VT_VARIANT, then we need to extract the
- // inner VARIANT and use it instead of the outer one. Note that if the inner VARIANT
- // is VT_BYREF | VT_VARIANT | VT_ARRAY, it will pass the below test too.
- Variant *pByRefVariant = (Variant *)pSrc->AsByRefVariant;
- if ((pByRefVariant->VariantType & VT_BYREF_TYPEMASK) == VT_BYREF_VARIANT)
- return (Variant *)pByRefVariant;
- }
-
- return pSrc;
- }
-
- unsafe void NativeMethods.IDispatch.Invoke(
- int dispid,
- ref Guid riid,
- int lcid,
- ComTypes.INVOKEKIND wFlags,
- ref ComTypes.DISPPARAMS pDispParams,
- IntPtr pvarResult,
- IntPtr pExcepInfo,
- IntPtr puArgErr) {
-
- ComEventsMethod method = FindMethod(dispid);
- if (method == null)
- return;
-
- // notice the unsafe pointers we are using. This is to avoid unnecessary
- // arguments marshalling. see code:ComEventsHelper#ComEventsArgsMarshalling
-
- object [] args = new object[pDispParams.cArgs];
- int [] byrefsMap = new int[pDispParams.cArgs];
- bool [] usedArgs = new bool[pDispParams.cArgs];
-
- Variant* pvars = (Variant*)pDispParams.rgvarg;
- int* pNamedArgs = (int*)pDispParams.rgdispidNamedArgs;
-
- // copy the named args (positional) as specified
- int i;
- int pos;
- for (i = 0; i < pDispParams.cNamedArgs; i++) {
- pos = pNamedArgs[i];
-
- Variant* pvar = GetVariant(&pvars[i]);
- args[pos] = pvar->ToObject();
- usedArgs[pos] = true;
-
- if (pvar->IsByRef) {
- byrefsMap[pos] = i;
- } else {
- byrefsMap[pos] = -1;
- }
- }
-
- // copy the rest of the arguments in the reverse order
- pos = 0;
- for (; i < pDispParams.cArgs; i++) {
- // find the next unassigned argument
- while (usedArgs[pos]) {
- ++pos;
- }
-
- Variant* pvar = GetVariant(&pvars[pDispParams.cArgs - 1 - i]);
- args[pos] = pvar->ToObject();
-
- if (pvar->IsByRef)
- byrefsMap[pos] = pDispParams.cArgs - 1 - i;
- else
- byrefsMap[pos] = -1;
-
- pos++;
- }
-
- // Do the actual delegate invocation
- object result;
- result = method.Invoke(args);
-
- // convert result to VARIANT
- if (pvarResult != IntPtr.Zero) {
- Marshal.GetNativeVariantForObject(result, pvarResult);
- }
-
- // Now we need to marshal all the byrefs back
- for (i = 0; i < pDispParams.cArgs; i++) {
- int idxToPos = byrefsMap[i];
- if (idxToPos == -1)
- continue;
-
- GetVariant(&pvars[idxToPos])->CopyFromIndirect(args[i]);
- }
- }
-
-#endregion
-
static Guid IID_IManagedObject = new Guid("{C3FCC19E-A970-11D2-8B5A-00A0C9B7C9C4}");
CustomQueryInterfaceResult ICustomQueryInterface.GetInterface(ref Guid iid, out IntPtr ppv) {
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-/*==========================================================================
-**
-** Interface: IEnumerable
-**
-**
-** Purpose:
-** This interface is redefined here since the original IEnumerable interface
-** has all its methods marked as ecall's since it is a managed standard
-** interface. This interface is used from within the runtime to make a call
-** on the COM server directly when it implements the IEnumerable interface.
-**
-**
-==========================================================================*/
-namespace System.Runtime.InteropServices.ComTypes
-{
- using System;
-
- [Guid("496B0ABE-CDEE-11d3-88E8-00902754C43A")]
- internal interface IEnumerable
- {
- [DispId(-4)]
- System.Collections.IEnumerator GetEnumerator();
- }
-}
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-/*==========================================================================
-**
-** Interface: IEnumerator
-**
-**
-** Purpose:
-** This interface is redefined here since the original IEnumerator interface
-** has all its methods marked as ecall's since it is a managed standard
-** interface. This interface is used from within the runtime to make a call
-** on the COM server directly when it implements the IEnumerator interface.
-**
-**
-==========================================================================*/
-namespace System.Runtime.InteropServices.ComTypes
-{
- using System;
-
- [Guid("496B0ABF-CDEE-11d3-88E8-00902754C43A")]
- internal interface IEnumerator
- {
- bool MoveNext();
-
- Object Current
- {
- get;
- }
-
- void Reset();
- }
-}
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-/*==========================================================================
-**
-** Interface: IExpando
-**
-**
-** Purpose:
-** This interface is redefined here since the original IExpando interface
-** has all its methods marked as ecall's since it is a managed standard
-** interface. This interface is used from within the runtime to make a call
-** on the COM server directly when it implements the IExpando interface.
-**
-**
-==========================================================================*/
-namespace System.Runtime.InteropServices.ComTypes
-{
- using System;
- using System.Reflection;
-
- [Guid("AFBF15E6-C37C-11d2-B88E-00A0C9B471B8")]
- internal interface IExpando : IReflect
- {
- FieldInfo AddField(String name);
- PropertyInfo AddProperty(String name);
- MethodInfo AddMethod(String name, Delegate method);
- void RemoveMember(MemberInfo m);
- }
-}
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-/*==========================================================================
-**
-** Interface: IReflect
-**
-**
-** Purpose:
-** This interface is redefined here since the original IReflect interface
-** has all its methods marked as ecall's since it is a managed standard
-** interface. This interface is used from within the runtime to make a call
-** on the COM server directly when it implements the IReflect interface.
-**
-**
-==========================================================================*/
-namespace System.Runtime.InteropServices.ComTypes
-{
- using System;
- using System.Reflection;
- using CultureInfo = System.Globalization.CultureInfo;
-
- [Guid("AFBF15E5-C37C-11d2-B88E-00A0C9B471B8")]
- internal interface IReflect
- {
- MethodInfo GetMethod(String name,BindingFlags bindingAttr,Binder binder,
- Type[] types,ParameterModifier[] modifiers);
-
- MethodInfo GetMethod(String name,BindingFlags bindingAttr);
-
- MethodInfo[] GetMethods(
- BindingFlags bindingAttr);
-
- FieldInfo GetField(
- String name,
- BindingFlags bindingAttr);
-
- FieldInfo[] GetFields(
- BindingFlags bindingAttr);
-
- PropertyInfo GetProperty(
- String name,
- BindingFlags bindingAttr);
-
- PropertyInfo GetProperty(
- String name,
- BindingFlags bindingAttr,
- Binder binder,
- Type returnType,
- Type[] types,
- ParameterModifier[] modifiers);
-
- PropertyInfo[] GetProperties(
- BindingFlags bindingAttr);
-
- MemberInfo[] GetMember(
- String name,
- BindingFlags bindingAttr);
-
- MemberInfo[] GetMembers(
- BindingFlags bindingAttr);
-
- Object InvokeMember(
- String name,
- BindingFlags invokeAttr,
- Binder binder,
- Object target,
- Object[] args,
- ParameterModifier[] modifiers,
- CultureInfo culture,
- String[] namedParameters);
-
- Type UnderlyingSystemType
- {
- get;
- }
- }
-}
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-/*=============================================================================
-**
-**
-**
-** Purpose: Methods used to customize the creation of managed objects that
-** extend from unmanaged objects.
-**
-**
-=============================================================================*/
-
-namespace System.Runtime.InteropServices {
- using System.Runtime.InteropServices;
- using System.Runtime.Remoting;
- using System.Runtime.CompilerServices;
- using System.Runtime.Versioning;
-
- using System;
-[System.Runtime.InteropServices.ComVisible(true)]
- public sealed class ExtensibleClassFactory
- {
-
- // Prevent instantiation.
- private ExtensibleClassFactory() {}
-
- // Register a delegate that will be called whenever an instance of a managed
- // type that extends from an unmanaged type needs to allocate the aggregated
- // unmanaged object. This delegate is expected to allocate and aggregate the
- // unmanaged object and is called in place of a CoCreateInstance. This
- // routine must be called in the context of the static initializer for the
- // class for which the callbacks will be made.
- // It is not legal to register this callback from a class that has any
- // parents that have already registered a callback.
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- public static extern void RegisterObjectCreationCallback(ObjectCreationDelegate callback);
- }
-}
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// 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 interface provides services for registering and unregistering
-** a managed server for use by COM.
-**
-**
-=============================================================================*/
-
-namespace System.Runtime.InteropServices {
-
- using System;
- using System.Reflection;
- using System.Security;
- using System.Security.Permissions;
-
- [Flags()]
-[System.Runtime.InteropServices.ComVisible(true)]
- public enum AssemblyRegistrationFlags
- {
- None = 0x00000000,
- SetCodeBase = 0x00000001,
- }
-
- [Guid("CCBD682C-73A5-4568-B8B0-C7007E11ABA2")]
-[System.Runtime.InteropServices.ComVisible(true)]
- public interface IRegistrationServices
- {
- bool RegisterAssembly(Assembly assembly, AssemblyRegistrationFlags flags);
-
- bool UnregisterAssembly(Assembly assembly);
-
- Type[] GetRegistrableTypesInAssembly(Assembly assembly);
-
- String GetProgIdForType(Type type);
-
- void RegisterTypeForComClients(Type type, ref Guid g);
-
- Guid GetManagedCategoryGuid();
-
- bool TypeRequiresRegistration(Type type);
-
- bool TypeRepresentsComType(Type type);
- }
-}
using System.Reflection;
using System.Reflection.Emit;
-[Serializable]
-[Flags()]
-[System.Runtime.InteropServices.ComVisible(true)]
- public enum TypeLibImporterFlags
- {
- None = 0x00000000,
- PrimaryInteropAssembly = 0x00000001,
- UnsafeInterfaces = 0x00000002,
- SafeArrayAsSystemArray = 0x00000004,
- TransformDispRetVals = 0x00000008,
- PreventClassMembers = 0x00000010,
- SerializableValueClasses = 0x00000020,
- ImportAsX86 = 0x00000100,
- ImportAsX64 = 0x00000200,
- ImportAsItanium = 0x00000400,
- ImportAsAgnostic = 0x00000800,
- ReflectionOnlyLoading = 0x00001000,
- NoDefineVersionResource = 0x00002000,
- ImportAsArm = 0x00004000,
- }
-
-[Serializable]
-[Flags()]
-[System.Runtime.InteropServices.ComVisible(true)]
- public enum TypeLibExporterFlags
- {
- None = 0x00000000,
- OnlyReferenceRegistered = 0x00000001,
- CallerResolvedReferences = 0x00000002,
- OldNames = 0x00000004,
- ExportAs32Bit = 0x00000010,
- ExportAs64Bit = 0x00000020,
- }
-
[Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public enum ImporterEventKind
NOTIF_CONVERTWARNING = 1,
ERROR_REFTOINVALIDASSEMBLY = 2
}
-
- [GuidAttribute("F1C3BF76-C3E4-11d3-88E7-00902754C43A")]
- [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
-[System.Runtime.InteropServices.ComVisible(true)]
- public interface ITypeLibImporterNotifySink
- {
- void ReportEvent(
- ImporterEventKind eventKind,
- int eventCode,
- String eventMsg);
- Assembly ResolveRef(
- [MarshalAs(UnmanagedType.Interface)] Object typeLib);
- }
-
- [GuidAttribute("F1C3BF77-C3E4-11d3-88E7-00902754C43A")]
- [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
-[System.Runtime.InteropServices.ComVisible(true)]
- public interface ITypeLibExporterNotifySink
- {
- void ReportEvent(
- ExporterEventKind eventKind,
- int eventCode,
- String eventMsg);
-
- [return : MarshalAs(UnmanagedType.Interface)]
- Object ResolveRef(
- Assembly assembly);
- }
-
- [GuidAttribute("F1C3BF78-C3E4-11d3-88E7-00902754C43A")]
- [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
-[System.Runtime.InteropServices.ComVisible(true)]
- public interface ITypeLibConverter
- {
- AssemblyBuilder ConvertTypeLibToAssembly(
- [MarshalAs(UnmanagedType.Interface)] Object typeLib,
- String asmFileName,
- TypeLibImporterFlags flags,
- ITypeLibImporterNotifySink notifySink,
- byte[] publicKey,
- StrongNameKeyPair keyPair,
- String asmNamespace,
- Version asmVersion);
-
- [return : MarshalAs(UnmanagedType.Interface)]
- Object ConvertAssemblyToTypeLib(
- Assembly assembly,
- String typeLibName,
- TypeLibExporterFlags flags,
- ITypeLibExporterNotifySink notifySink);
-
- bool GetPrimaryInteropAssembly(Guid g, Int32 major, Int32 minor, Int32 lcid, out String asmName, out String asmCodeBase);
-
- AssemblyBuilder ConvertTypeLibToAssembly([MarshalAs(UnmanagedType.Interface)] Object typeLib,
- String asmFileName,
- int flags,
- ITypeLibImporterNotifySink notifySink,
- byte[] publicKey,
- StrongNameKeyPair keyPair,
- bool unsafeInterfaces);
- }
-
- [GuidAttribute("FA1F3615-ACB9-486d-9EAC-1BEF87E36B09")]
- [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
-[System.Runtime.InteropServices.ComVisible(true)]
- public interface ITypeLibExporterNameProvider
- {
- [return : MarshalAs(UnmanagedType.SafeArray, SafeArraySubType=VarEnum.VT_BSTR)]
- String[] GetNames();
- }
}
}
}
- //====================================================================
- // NumParamBytes
- //====================================================================
- public static int NumParamBytes(MethodInfo m)
- {
- if (m == null)
- throw new ArgumentNullException(nameof(m));
- Contract.EndContractBlock();
-
- RuntimeMethodInfo rmi = m as RuntimeMethodInfo;
- if (rmi == null)
- throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeMethodInfo"));
-
- return InternalNumParamBytes(rmi);
- }
-
- [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity]
- private static extern int InternalNumParamBytes(IRuntimeMethodInfo m);
-
- //====================================================================
- // Win32 Exception stuff
- // These are mostly interesting for Structured exception handling,
- // but need to be exposed for all exceptions (not just SEHException).
- //====================================================================
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- [System.Runtime.InteropServices.ComVisible(true)]
- public static extern /* struct _EXCEPTION_POINTERS* */ IntPtr GetExceptionPointers();
-
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern int GetExceptionCode();
//====================================================================
- // This method is intended for compiler code generators rather
- // than applications.
- //====================================================================
- [ObsoleteAttribute("The GetUnmanagedThunkForManagedMethodPtr method has been deprecated and will be removed in a future release.", false)]
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- public static extern IntPtr GetUnmanagedThunkForManagedMethodPtr(IntPtr pfnMethodToWrap, IntPtr pbSignature, int cbSignature);
-
- //====================================================================
- // This method is intended for compiler code generators rather
- // than applications.
- //====================================================================
- [ObsoleteAttribute("The GetManagedThunkForUnmanagedMethodPtr method has been deprecated and will be removed in a future release.", false)]
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- public static extern IntPtr GetManagedThunkForUnmanagedMethodPtr(IntPtr pfnMethodToWrap, IntPtr pbSignature, int cbSignature);
-
- //====================================================================
- // The hosting APIs allow a sophisticated host to schedule fibers
- // onto OS threads, so long as they notify the runtime of this
- // activity. A fiber cookie can be redeemed for its managed Thread
- // object by calling the following service.
- //====================================================================
- [ObsoleteAttribute("The GetThreadFromFiberCookie method has been deprecated. Use the hosting API to perform this operation.", false)]
- public static Thread GetThreadFromFiberCookie(int cookie)
- {
- if (cookie == 0)
- throw new ArgumentException(Environment.GetResourceString("Argument_ArgumentZero"), nameof(cookie));
- Contract.EndContractBlock();
-
- return InternalGetThreadFromFiberCookie(cookie);
- }
-
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- private static extern Thread InternalGetThreadFromFiberCookie(int cookie);
-
-
- //====================================================================
// Memory allocation and deallocation.
//====================================================================
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
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 a UCOMITypeLib, return its name
- //====================================================================
- [Obsolete("Use System.Runtime.InteropServices.Marshal.GetTypeLibName(ITypeLib pTLB) instead. http://go.microsoft.com/fwlink/?linkid=14202&ID=0000011.", false)]
- public static String GetTypeLibName(UCOMITypeLib pTLB)
- {
- return GetTypeLibName((ITypeLib)pTLB);
- }
-
-
- //====================================================================
- // Given a managed object that wraps an ITypeLib, return its name
- //====================================================================
- public static String GetTypeLibName(ITypeLib typelib)
- {
- if (typelib == null)
- throw new ArgumentNullException(nameof(typelib));
- Contract.EndContractBlock();
-
- String strTypeLibName = null;
- String strDocString = null;
- int dwHelpContext = 0;
- String strHelpFile = null;
-
- typelib.GetDocumentation(-1, out strTypeLibName, out strDocString, out dwHelpContext, out strHelpFile);
-
- return strTypeLibName;
- }
-
- //====================================================================
- // Internal version of GetTypeLibName
- // Support GUID_ManagedName which aligns with TlbImp
- //====================================================================
- internal static String GetTypeLibNameInternal(ITypeLib typelib)
- {
- if (typelib == null)
- throw new ArgumentNullException(nameof(typelib));
- Contract.EndContractBlock();
-
- // Try GUID_ManagedName first
- ITypeLib2 typeLib2 = typelib as ITypeLib2;
- if (typeLib2 != null)
- {
- Guid guid = ManagedNameGuid;
- object val;
-
- try
- {
- typeLib2.GetCustData(ref guid, out val);
- }
- catch(Exception)
- {
- val = null;
- }
-
- if (val != null && val.GetType() == typeof(string))
- {
- string customManagedNamespace = (string)val;
- customManagedNamespace = customManagedNamespace.Trim();
- if (customManagedNamespace.EndsWith(".DLL", StringComparison.OrdinalIgnoreCase))
- customManagedNamespace = customManagedNamespace.Substring(0, customManagedNamespace.Length - 4);
- else if (customManagedNamespace.EndsWith(".EXE", StringComparison.OrdinalIgnoreCase))
- customManagedNamespace = customManagedNamespace.Substring(0, customManagedNamespace.Length - 4);
- return customManagedNamespace;
- }
- }
-
- return GetTypeLibName(typelib);
- }
-
-
- //====================================================================
- // Given an managed object that wraps an UCOMITypeLib, return its guid
- //====================================================================
- [Obsolete("Use System.Runtime.InteropServices.Marshal.GetTypeLibGuid(ITypeLib pTLB) instead. http://go.microsoft.com/fwlink/?linkid=14202&ID=0000011.", false)]
- public static Guid GetTypeLibGuid(UCOMITypeLib pTLB)
- {
- return GetTypeLibGuid((ITypeLib)pTLB);
- }
-
- //====================================================================
- // Given an managed object that wraps an ITypeLib, return its guid
- //====================================================================
- public static Guid GetTypeLibGuid(ITypeLib typelib)
- {
- Guid result = new Guid ();
- FCallGetTypeLibGuid (ref result, typelib);
- return result;
- }
-
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- private static extern void FCallGetTypeLibGuid(ref Guid result, ITypeLib pTLB);
-
- //====================================================================
- // Given a managed object that wraps a UCOMITypeLib, return its lcid
- //====================================================================
- [Obsolete("Use System.Runtime.InteropServices.Marshal.GetTypeLibLcid(ITypeLib pTLB) instead. http://go.microsoft.com/fwlink/?linkid=14202&ID=0000011.", false)]
- public static int GetTypeLibLcid(UCOMITypeLib pTLB)
- {
- return GetTypeLibLcid((ITypeLib)pTLB);
- }
-
- //====================================================================
- // Given a managed object that wraps an ITypeLib, return its lcid
- //====================================================================
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- public static extern int GetTypeLibLcid(ITypeLib typelib);
-
- //====================================================================
- // Given a managed object that wraps an ITypeLib, return it's
- // version information.
- //====================================================================
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- internal static extern void GetTypeLibVersion(ITypeLib typeLibrary, out int major, out int minor);
-
- //====================================================================
- // Given a managed object that wraps an ITypeInfo, return its guid.
- //====================================================================
- internal static Guid GetTypeInfoGuid(ITypeInfo typeInfo)
- {
- Guid result = new Guid ();
- FCallGetTypeInfoGuid (ref result, typeInfo);
- return result;
- }
-
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- private static extern void FCallGetTypeInfoGuid(ref Guid result, ITypeInfo typeInfo);
-
- //====================================================================
- // Given a assembly, return the TLBID that will be generated for the
- // typelib exported from the assembly.
- //====================================================================
- public static Guid GetTypeLibGuidForAssembly(Assembly asm)
- {
- if (asm == null)
- throw new ArgumentNullException(nameof(asm));
- Contract.EndContractBlock();
-
- RuntimeAssembly rtAssembly = asm as RuntimeAssembly;
- if (rtAssembly == null)
- throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeAssembly"), nameof(asm));
-
- Guid result = new Guid();
- FCallGetTypeLibGuidForAssembly(ref result, rtAssembly);
- return result;
- }
-
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- private static extern void FCallGetTypeLibGuidForAssembly(ref Guid result, RuntimeAssembly asm);
-
- //====================================================================
- // Given a assembly, return the version number of the type library
- // that would be exported from the assembly.
- //====================================================================
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- private static extern void _GetTypeLibVersionForAssembly(RuntimeAssembly inputAssembly, out int majorVersion, out int minorVersion);
-
- public static void GetTypeLibVersionForAssembly(Assembly inputAssembly, out int majorVersion, out int minorVersion)
- {
- if (inputAssembly == null)
- throw new ArgumentNullException(nameof(inputAssembly));
- Contract.EndContractBlock();
-
- RuntimeAssembly rtAssembly = inputAssembly as RuntimeAssembly;
- if (rtAssembly == null)
- throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeAssembly"), nameof(inputAssembly));
-
- _GetTypeLibVersionForAssembly(rtAssembly, out majorVersion, out minorVersion);
- }
-
- //====================================================================
- // Given a managed object that wraps an UCOMITypeInfo, return its name
- //====================================================================
- [Obsolete("Use System.Runtime.InteropServices.Marshal.GetTypeInfoName(ITypeInfo pTLB) instead. http://go.microsoft.com/fwlink/?linkid=14202&ID=0000011.", false)]
- public static String GetTypeInfoName(UCOMITypeInfo pTI)
- {
- return GetTypeInfoName((ITypeInfo)pTI);
- }
//====================================================================
// Given a managed object that wraps an ITypeInfo, return its name
return strTypeLibName;
}
- //====================================================================
- // Internal version of GetTypeInfoName
- // Support GUID_ManagedName which aligns with TlbImp
- //====================================================================
- internal static String GetTypeInfoNameInternal(ITypeInfo typeInfo, out bool hasManagedName)
- {
- if (typeInfo == null)
- throw new ArgumentNullException(nameof(typeInfo));
- Contract.EndContractBlock();
-
- // Try ManagedNameGuid first
- ITypeInfo2 typeInfo2 = typeInfo as ITypeInfo2;
- if (typeInfo2 != null)
- {
- Guid guid = ManagedNameGuid;
- object val;
-
- try
- {
- typeInfo2.GetCustData(ref guid, out val);
- }
- catch(Exception)
- {
- val = null;
- }
-
- if (val != null && val.GetType() == typeof(string))
- {
- hasManagedName = true;
- return (string)val;
- }
- }
-
- hasManagedName = false;
- return GetTypeInfoName(typeInfo);
- }
-
- //====================================================================
- // Get the corresponding managed name as converted by TlbImp
- // Used to get the type using GetType() from imported assemblies
- //====================================================================
- internal static String GetManagedTypeInfoNameInternal(ITypeLib typeLib, ITypeInfo typeInfo)
- {
- bool hasManagedName;
- string name = GetTypeInfoNameInternal(typeInfo, out hasManagedName);
- if (hasManagedName)
- return name;
- else
- return GetTypeLibNameInternal(typeLib) + "." + name;
- }
-
- //====================================================================
- // If a type with the specified GUID is loaded, this method will
- // return the reflection type that represents it. Otherwise it returns
- // NULL.
- //====================================================================
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- private static extern Type GetLoadedTypeForGUID(ref Guid guid);
-
// 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)
}
//====================================================================
- // map Type to ITypeInfo*
- //====================================================================
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- public static extern IntPtr /* ITypeInfo* */ GetITypeInfoForType(Type t);
-
- //====================================================================
// return the IUnknown* for an Object if the current context
// is the one where the RCW was first seen. Will return null
// otherwise.
return GetIUnknownForObjectNative(o, false);
}
- public static IntPtr /* IUnknown* */ GetIUnknownForObjectInContext(Object o)
- {
- return GetIUnknownForObjectNative(o, true);
- }
-
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern IntPtr /* IUnknown* */ GetIUnknownForObjectNative(Object o, bool onlyInContext);
}
#if FEATURE_COMINTEROP
- //====================================================================
- // return the IDispatch* for an Object if the current context
- // is the one where the RCW was first seen. Will return null
- // otherwise.
- //====================================================================
- public static IntPtr /* IUnknown* */ GetIDispatchForObjectInContext(Object o)
- {
- return GetIDispatchForObjectNative(o, true);
- }
-
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- private static extern IntPtr /* IUnknown* */ GetIDispatchForObjectNative(Object o, bool onlyInContext);
//====================================================================
// return the IUnknown* representing the interface for the Object
return GetComInterfaceForObjectNative(o, T, false, bEnableCustomizedQueryInterface);
}
- //====================================================================
- // return the IUnknown* representing the interface for the Object
- // Object o should support Type T if the current context
- // is the one where the RCW was first seen. Will return null
- // otherwise.
- //====================================================================
- public static IntPtr /* IUnknown* */ GetComInterfaceForObjectInContext(Object o, Type t)
- {
- return GetComInterfaceForObjectNative(o, t, true, true);
- }
-
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern IntPtr /* IUnknown* */ GetComInterfaceForObjectNative(Object o, Type t, bool onlyInContext, bool fEnalbeCustomizedQueryInterface);
private static extern Object InternalCreateWrapperOfType(Object o, Type t);
//====================================================================
- // There may be a thread-based cache of COM components. This service can
- // force the aggressive release of the current thread's cache.
- //====================================================================
- [Obsolete("This API did not perform any operation and will be removed in future versions of the CLR.", false)]
- public static void ReleaseThreadCache()
- {
- }
-
- //====================================================================
- // check if the type is visible from COM.
- //====================================================================
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- public static extern bool IsTypeVisibleFromCom(Type t);
-
- //====================================================================
// IUnknown Helpers
//====================================================================
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern int GetStartComSlot(Type t);
- /// <summary>
- /// <para>Returns the last valid COM slot that GetMethodInfoForSlot will work on. </para>
- /// </summary>
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- public static extern int GetEndComSlot(Type t);
-
- /// <summary>
- /// <para>Returns the MemberInfo that COM callers calling through the exposed
- /// vtable on the given slot will be calling. The slot should take into account
- /// if the exposed interface is IUnknown based or IDispatch based.
- /// For classes, the lookup is done on the default interface that will be
- /// exposed for the class. </para>
- /// </summary>
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- public static extern MemberInfo GetMethodInfoForComSlot(Type t, int slot, ref ComMemberType memberType);
-
- /// <summary>
- /// <para>Returns the COM slot for a memeber info, taking into account whether
- /// the exposed interface is IUnknown based or IDispatch based</para>
- /// </summary>
- public static int GetComSlotForMethodInfo(MemberInfo m)
- {
- if (m== null)
- throw new ArgumentNullException(nameof(m));
-
- if (!(m is RuntimeMethodInfo))
- throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeMethodInfo"), nameof(m));
-
- if (!m.DeclaringType.IsInterface)
- throw new ArgumentException(Environment.GetResourceString("Argument_MustBeInterfaceMethod"), nameof(m));
- if (m.DeclaringType.IsGenericType)
- throw new ArgumentException(Environment.GetResourceString("Argument_NeedNonGenericType"), nameof(m));
- Contract.EndContractBlock();
-
- return InternalGetComSlotForMethodInfo((IRuntimeMethodInfo)m);
- }
-
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- private static extern int InternalGetComSlotForMethodInfo(IRuntimeMethodInfo m);
#endif // FEATURE_COMINTEROP
//====================================================================
return obj;
}
- //====================================================================
- // This method gets the currently running object.
- //====================================================================
- public static Object GetActiveObject(String progID)
- {
- Object obj = null;
- Guid clsid;
-
- // Call CLSIDFromProgIDEx first then fall back on CLSIDFromProgID if
- // CLSIDFromProgIDEx doesn't exist.
- try
- {
- CLSIDFromProgIDEx(progID, out clsid);
- }
-// catch
- catch(Exception)
- {
- CLSIDFromProgID(progID, out clsid);
- }
-
- GetActiveObject(ref clsid, IntPtr.Zero, out obj);
- return obj;
- }
-
- [DllImport(Microsoft.Win32.Win32Native.OLE32, PreserveSig = false)]
- [SuppressUnmanagedCodeSecurity]
- private static extern void CLSIDFromProgIDEx([MarshalAs(UnmanagedType.LPWStr)] String progId, out Guid clsid);
-
- [DllImport(Microsoft.Win32.Win32Native.OLE32, PreserveSig = false)]
- [SuppressUnmanagedCodeSecurity]
- private static extern void CLSIDFromProgID([MarshalAs(UnmanagedType.LPWStr)] String progId, out Guid clsid);
-
[DllImport(Microsoft.Win32.Win32Native.OLE32, PreserveSig = false)]
[SuppressUnmanagedCodeSecurity]
private static extern void CreateBindCtx(UInt32 reserved, out IBindCtx ppbc);
[SuppressUnmanagedCodeSecurity]
private static extern void BindMoniker(IMoniker pmk, UInt32 grfOpt, ref Guid iidResult, [MarshalAs(UnmanagedType.Interface)] out Object ppvResult);
- [DllImport(Microsoft.Win32.Win32Native.OLEAUT32, PreserveSig = false)]
- [SuppressUnmanagedCodeSecurity]
- private static extern void GetActiveObject(ref Guid rclsid, IntPtr reserved, [MarshalAs(UnmanagedType.Interface)] out Object ppunk);
-
- //========================================================================
- // Private method called from remoting to support ServicedComponents.
- //========================================================================
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- internal static extern bool InternalSwitchCCW(Object oldtp, Object newtp);
-
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- internal static extern Object InternalWrapIUnknownWithComObject(IntPtr i);
-
//========================================================================
// Private method called from EE upon use of license/ICF2 marshaling.
//========================================================================
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern object GetNativeActivationFactory(Type type);
- //========================================================================
- // Methods allowing retrieval of the IIDs exposed by an underlying WinRT
- // object, as specified by the object's IInspectable::GetIids()
- //========================================================================
- [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity]
- private static extern void _GetInspectableIids(ObjectHandleOnStack obj, ObjectHandleOnStack guids);
-
- internal static System.Guid[] GetInspectableIids(object obj)
- {
- System.Guid[] result = null;
- System.__ComObject comObj = obj as System.__ComObject;
- if (comObj != null)
- {
- _GetInspectableIids(JitHelpers.GetObjectHandleOnStack(ref comObj),
- JitHelpers.GetObjectHandleOnStack(ref result));
- }
-
- return result;
- }
-
- //========================================================================
- // Methods allowing retrieval of the cached WinRT type corresponding to
- // the specified GUID
- //========================================================================
- [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity]
- private static extern void _GetCachedWinRTTypeByIid(
- ObjectHandleOnStack appDomainObj,
- System.Guid iid,
- out IntPtr rthHandle);
-
- internal static System.Type GetCachedWinRTTypeByIid(
- System.AppDomain ad,
- System.Guid iid)
- {
- IntPtr rthHandle;
- _GetCachedWinRTTypeByIid(JitHelpers.GetObjectHandleOnStack(ref ad),
- iid,
- out rthHandle);
- System.Type res = Type.GetTypeFromHandleUnsafe(rthHandle);
- return res;
- }
-
-
- //========================================================================
- // Methods allowing retrieval of the WinRT types cached in the specified
- // app domain
- //========================================================================
- [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity]
- private static extern void _GetCachedWinRTTypes(
- ObjectHandleOnStack appDomainObj,
- ref int epoch,
- ObjectHandleOnStack winrtTypes);
-
- internal static System.Type[] GetCachedWinRTTypes(
- System.AppDomain ad,
- ref int epoch)
- {
- System.IntPtr[] res = null;
-
- _GetCachedWinRTTypes(JitHelpers.GetObjectHandleOnStack(ref ad),
- ref epoch,
- JitHelpers.GetObjectHandleOnStack(ref res));
-
- System.Type[] result = new System.Type[res.Length];
- for (int i = 0; i < res.Length; ++i)
- {
- result[i] = Type.GetTypeFromHandleUnsafe(res[i]);
- }
-
- return result;
- }
-
- internal static System.Type[] GetCachedWinRTTypes(
- System.AppDomain ad)
- {
- int dummyEpoch = 0;
- return GetCachedWinRTTypes(ad, ref dummyEpoch);
- }
-
-
#endif // FEATURE_COMINTEROP
public static Delegate GetDelegateForFunctionPointer(IntPtr ptr, Type t)
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-/*=============================================================================
-**
-** Delegate: ObjectCreationDelegate
-**
-**
-** Purpose: Delegate called to create a classic COM object as an alternative to
-** CoCreateInstance.
-**
-**
-=============================================================================*/
-
-namespace System.Runtime.InteropServices {
-
- // Delegate called when a managed object wishes to instantiate its unmanaged
- // portion. The IUnknown of the managed object (the aggregator) is passed as a
- // parameter and the delegate should return the IUnknown of the unmanaged object
- // (the aggregatee). Both are passed as int's to avoid any marshalling.
-[System.Runtime.InteropServices.ComVisible(true)]
- public delegate IntPtr ObjectCreationDelegate(IntPtr aggregator);
-}
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// 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 provides services for registering and unregistering
-** a managed server for use by COM.
-**
-**
-**
-**
-** Change the way how to register and unregister a managed server
-**
-=============================================================================*/
-namespace System.Runtime.InteropServices {
-
- using System;
- using System.Collections;
- using System.IO;
- using System.Reflection;
- using System.Security;
- using System.Security.Permissions;
- using System.Text;
- using System.Threading;
- using Microsoft.Win32;
- using System.Runtime.CompilerServices;
- using System.Globalization;
- using System.Runtime.Versioning;
- using System.Diagnostics;
- using System.Diagnostics.Contracts;
-
- [Flags]
- public enum RegistrationClassContext
- {
-
-
- InProcessServer = 0x1,
- InProcessHandler = 0x2,
- LocalServer = 0x4,
- InProcessServer16 = 0x8,
- RemoteServer = 0x10,
- InProcessHandler16 = 0x20,
- Reserved1 = 0x40,
- Reserved2 = 0x80,
- Reserved3 = 0x100,
- Reserved4 = 0x200,
- NoCodeDownload = 0x400,
- Reserved5 = 0x800,
- NoCustomMarshal = 0x1000,
- EnableCodeDownload = 0x2000,
- NoFailureLog = 0x4000,
- DisableActivateAsActivator = 0x8000,
- EnableActivateAsActivator = 0x10000,
- FromDefaultContext = 0x20000
- }
-
-
- [Flags]
- public enum RegistrationConnectionType
- {
- SingleUse = 0,
- MultipleUse = 1,
- MultiSeparate = 2,
- Suspended = 4,
- Surrogate = 8,
- }
-
- [Guid("475E398F-8AFA-43a7-A3BE-F4EF8D6787C9")]
- [ClassInterface(ClassInterfaceType.None)]
-[System.Runtime.InteropServices.ComVisible(true)]
- public class RegistrationServices : IRegistrationServices
- {
- #region Constants
-
- private const String strManagedCategoryGuid = "{62C8FE65-4EBB-45e7-B440-6E39B2CDBF29}";
- private const String strDocStringPrefix = "";
- private const String strManagedTypeThreadingModel = "Both";
- private const String strComponentCategorySubKey = "Component Categories";
- private const String strManagedCategoryDescription = ".NET Category";
- private const String strImplementedCategoriesSubKey = "Implemented Categories";
- private const String strMsCorEEFileName = "mscoree.dll";
- private const String strRecordRootName = "Record";
- private const String strClsIdRootName = "CLSID";
- private const String strTlbRootName = "TypeLib";
- private static Guid s_ManagedCategoryGuid = new Guid(strManagedCategoryGuid);
-
- #endregion
-
-
- #region IRegistrationServices
-
- public virtual bool RegisterAssembly(Assembly assembly, AssemblyRegistrationFlags flags)
- {
- // Validate the arguments.
- if (assembly == null)
- throw new ArgumentNullException(nameof(assembly));
-
- if (assembly.ReflectionOnly)
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_AsmLoadedForReflectionOnly"));
- Contract.EndContractBlock();
-
- RuntimeAssembly rtAssembly = assembly as RuntimeAssembly;
- if (rtAssembly == null)
- throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeAssembly"));
-
- // Retrieve the assembly names.
- String strAsmName = assembly.FullName;
- if (strAsmName == null)
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NoAsmName"));
-
- // Retrieve the assembly codebase.
- String strAsmCodeBase = null;
- if ((flags & AssemblyRegistrationFlags.SetCodeBase) != 0)
- {
- strAsmCodeBase = rtAssembly.GetCodeBase(false);
- if (strAsmCodeBase == null)
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NoAsmCodeBase"));
- }
-
- // Go through all the registerable types in the assembly and register them.
- Type[] aTypes = GetRegistrableTypesInAssembly(assembly);
- int NumTypes = aTypes.Length;
-
- String strAsmVersion = rtAssembly.GetVersion().ToString();
-
- // Retrieve the runtime version used to build the assembly.
- String strRuntimeVersion = assembly.ImageRuntimeVersion;
-
- for (int cTypes = 0; cTypes < NumTypes; cTypes++)
- {
- if (IsRegisteredAsValueType(aTypes[cTypes]))
- RegisterValueType(aTypes[cTypes], strAsmName, strAsmVersion, strAsmCodeBase, strRuntimeVersion);
- else if (TypeRepresentsComType(aTypes[cTypes]))
- RegisterComImportedType(aTypes[cTypes], strAsmName, strAsmVersion, strAsmCodeBase, strRuntimeVersion);
- else
- RegisterManagedType(aTypes[cTypes], strAsmName, strAsmVersion, strAsmCodeBase, strRuntimeVersion);
-
- CallUserDefinedRegistrationMethod(aTypes[cTypes], true);
- }
-
- // If this assembly has the PIA attribute, then register it as a PIA.
- Object[] aPIAAttrs = assembly.GetCustomAttributes(typeof(PrimaryInteropAssemblyAttribute), false);
- int NumPIAAttrs = aPIAAttrs.Length;
- for (int cPIAAttrs = 0; cPIAAttrs < NumPIAAttrs; cPIAAttrs++)
- RegisterPrimaryInteropAssembly(rtAssembly, strAsmCodeBase, (PrimaryInteropAssemblyAttribute)aPIAAttrs[cPIAAttrs]);
-
- // Return value indicating if we actually registered any types.
- if (aTypes.Length > 0 || NumPIAAttrs > 0)
- return true;
- else
- return false;
- }
-
- public virtual bool UnregisterAssembly(Assembly assembly)
- {
- // Validate the arguments.
- if (assembly == null)
- throw new ArgumentNullException(nameof(assembly));
-
- if (assembly.ReflectionOnly)
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_AsmLoadedForReflectionOnly"));
- Contract.EndContractBlock();
-
- RuntimeAssembly rtAssembly = assembly as RuntimeAssembly;
- if (rtAssembly == null)
- throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeAssembly"));
-
- bool bAllVersionsGone = true;
-
- // Go through all the registrable types in the assembly and register them.
- Type[] aTypes = GetRegistrableTypesInAssembly(assembly);
- int NumTypes = aTypes.Length;
-
- // Retrieve the assembly version
- String strAsmVersion = rtAssembly.GetVersion().ToString();
- for (int cTypes = 0;cTypes < NumTypes;cTypes++)
- {
- CallUserDefinedRegistrationMethod(aTypes[cTypes], false);
-
- if (IsRegisteredAsValueType(aTypes[cTypes]))
- {
- if (!UnregisterValueType(aTypes[cTypes], strAsmVersion))
- bAllVersionsGone = false;
- }
- else if (TypeRepresentsComType(aTypes[cTypes]))
- {
- if (!UnregisterComImportedType(aTypes[cTypes], strAsmVersion))
- bAllVersionsGone = false;
- }
- else
- {
- if (!UnregisterManagedType(aTypes[cTypes], strAsmVersion))
- bAllVersionsGone = false;
- }
- }
-
- // If this assembly has the PIA attribute, then unregister it as a PIA.
- Object[] aPIAAttrs = assembly.GetCustomAttributes(typeof(PrimaryInteropAssemblyAttribute),false);
- int NumPIAAttrs = aPIAAttrs.Length;
- if (bAllVersionsGone)
- {
- for (int cPIAAttrs = 0;cPIAAttrs < NumPIAAttrs;cPIAAttrs++)
- UnregisterPrimaryInteropAssembly(assembly, (PrimaryInteropAssemblyAttribute)aPIAAttrs[cPIAAttrs]);
- }
-
- // Return value indicating if we actually un-registered any types.
- if (aTypes.Length > 0 || NumPIAAttrs > 0)
- return true;
- else
- return false;
- }
-
- public virtual Type[] GetRegistrableTypesInAssembly(Assembly assembly)
- {
- // Validate the arguments.
- if (assembly == null)
- throw new ArgumentNullException(nameof(assembly));
- Contract.EndContractBlock();
-
- if (!(assembly is RuntimeAssembly))
- throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeAssembly"), nameof(assembly));
-
- // Retrieve the list of types in the assembly.
- Type[] aTypes = assembly.GetExportedTypes();
- int NumTypes = aTypes.Length;
-
- // Create an array list that will be filled in.
- ArrayList TypeList = new ArrayList();
-
- // Register all the types that require registration.
- for (int cTypes = 0; cTypes < NumTypes; cTypes++)
- {
- Type CurrentType = aTypes[cTypes];
- if (TypeRequiresRegistration(CurrentType))
- TypeList.Add(CurrentType);
- }
-
- // Copy the array list to an array and return it.
- Type[] RetArray = new Type[TypeList.Count];
- TypeList.CopyTo(RetArray);
- return RetArray;
- }
-
- public virtual String GetProgIdForType(Type type)
- {
- return Marshal.GenerateProgIdForType(type);
- }
-
- public virtual void RegisterTypeForComClients(Type type, ref Guid g)
- {
-#if FEATURE_COMINTEROP_MANAGED_ACTIVATION
- if(type == null)
- throw new ArgumentNullException(nameof(type));
- Contract.EndContractBlock();
- if((type as RuntimeType) == null)
- throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType"),nameof(type));
- if(!TypeRequiresRegistration(type))
- throw new ArgumentException(Environment.GetResourceString("Argument_TypeMustBeComCreatable"),nameof(type));
-
- // Call the native method to do CoRegisterClassObject
- RegisterTypeForComClientsNative(type, ref g);
-#else // FEATURE_COMINTEROP_MANAGED_ACTIVATION
- throw new NotImplementedException("CoreCLR_REMOVED -- managed activation removed");
-#endif // FEATURE_COMINTEROP_MANAGED_ACTIVATION
- }
-
- public virtual Guid GetManagedCategoryGuid()
- {
- return s_ManagedCategoryGuid;
- }
-
- public virtual bool TypeRequiresRegistration(Type type)
- {
- return TypeRequiresRegistrationHelper(type);
- }
-
- public virtual bool TypeRepresentsComType(Type type)
- {
- // If the type is not a COM import, then it does not represent a COM type.
- if (!type.IsCOMObject)
- return false;
-
- // If it is marked as tdImport, then it represents a COM type directly.
- if (type.IsImport)
- return true;
-
- // If the type is derived from a tdImport class and has the same GUID as the
- // imported class, then it represents a COM type.
- Type baseComImportType = GetBaseComImportType(type);
- Debug.Assert(baseComImportType != null, "baseComImportType != null");
- if (Marshal.GenerateGuidForType(type) == Marshal.GenerateGuidForType(baseComImportType))
- return true;
-
- return false;
- }
-
- #endregion
-
-
- #region Public methods not on IRegistrationServices
- [ComVisible(false)]
- public virtual int RegisterTypeForComClients(Type type, RegistrationClassContext classContext, RegistrationConnectionType flags)
- {
-#if FEATURE_COMINTEROP_MANAGED_ACTIVATION
- if (type == null)
- throw new ArgumentNullException(nameof(type));
- Contract.EndContractBlock();
- if ((type as RuntimeType) == null)
- throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType"),nameof(type));
- if (!TypeRequiresRegistration(type))
- throw new ArgumentException(Environment.GetResourceString("Argument_TypeMustBeComCreatable"),nameof(type));
-
- // Call the native method to do CoRegisterClassObject
- return RegisterTypeForComClientsExNative(type, classContext, flags);
-#else // FEATURE_COMINTEROP_MANAGED_ACTIVATION
- throw new NotImplementedException("CoreCLR_REMOVED -- managed activation removed");
-#endif // FEATURE_COMINTEROP_MANAGED_ACTIVATION
- }
-
- [ComVisible(false)]
- public virtual void UnregisterTypeForComClients(int cookie)
- {
- // Call the native method to do CoRevokeClassObject.
- CoRevokeClassObject(cookie);
- }
-
- #endregion
-
-
- #region Internal helpers
-
- internal static bool TypeRequiresRegistrationHelper(Type type)
- {
- // If the type is not a class or a value class, then it does not get registered.
- if (!type.IsClass && !type.IsValueType)
- return false;
-
- // If the type is abstract then it does not get registered.
- if (type.IsAbstract)
- return false;
-
- // If the does not have a public default constructor then is not creatable from COM so
- // it does not require registration unless it is a value class.
- if (!type.IsValueType && type.GetConstructor(BindingFlags.Instance | BindingFlags.Public,null,Array.Empty<Type>(),null) == null)
- return false;
-
- // All other conditions are met so check to see if the type is visible from COM.
- return Marshal.IsTypeVisibleFromCom(type);
- }
-
- #endregion
-
-
- #region Private helpers
-
- private void RegisterValueType(Type type, String strAsmName, String strAsmVersion, String strAsmCodeBase, String strRuntimeVersion)
- {
- // Retrieve some information that will be used during the registration process.
- String strRecordId = "{" + Marshal.GenerateGuidForType(type).ToString().ToUpper(CultureInfo.InvariantCulture) + "}";
-
- // Create the HKEY_CLASS_ROOT\Record key.
- using (RegistryKey RecordRootKey = Registry.ClassesRoot.CreateSubKey(strRecordRootName))
- {
- // Create the HKEY_CLASS_ROOT\Record\<RecordID> key.
- using (RegistryKey RecordKey = RecordRootKey.CreateSubKey(strRecordId))
- {
- // Create the HKEY_CLASS_ROOT\Record\<RecordId>\<version> key.
- using (RegistryKey RecordVersionKey = RecordKey.CreateSubKey(strAsmVersion))
- {
- // Set the class value.
- RecordVersionKey.SetValue("Class", type.FullName);
-
- // Set the assembly value.
- RecordVersionKey.SetValue("Assembly", strAsmName);
-
- // Set the runtime version value.
- RecordVersionKey.SetValue("RuntimeVersion", strRuntimeVersion);
-
- // Set the assembly code base value if a code base was specified.
- if (strAsmCodeBase != null)
- RecordVersionKey.SetValue("CodeBase", strAsmCodeBase);
- }
- }
- }
- }
-
- private void RegisterManagedType(Type type, String strAsmName, String strAsmVersion, String strAsmCodeBase, String strRuntimeVersion)
- {
- //
- // Retrieve some information that will be used during the registration process.
- //
-
- String strDocString = strDocStringPrefix + type.FullName;
- String strClsId = "{" + Marshal.GenerateGuidForType(type).ToString().ToUpper(CultureInfo.InvariantCulture) + "}";
- String strProgId = GetProgIdForType(type);
-
-
- //
- // Write the actual type information in the registry.
- //
-
- if (strProgId != String.Empty)
- {
- // Create the HKEY_CLASS_ROOT\<wzProgId> key.
- using (RegistryKey TypeNameKey = Registry.ClassesRoot.CreateSubKey(strProgId))
- {
- TypeNameKey.SetValue("", strDocString);
-
- // Create the HKEY_CLASS_ROOT\<wzProgId>\CLSID key.
- using (RegistryKey ProgIdClsIdKey = TypeNameKey.CreateSubKey("CLSID"))
- {
- ProgIdClsIdKey.SetValue("", strClsId);
- }
- }
- }
-
- // Create the HKEY_CLASS_ROOT\CLSID key.
- using (RegistryKey ClsIdRootKey = Registry.ClassesRoot.CreateSubKey(strClsIdRootName))
- {
- // Create the HKEY_CLASS_ROOT\CLSID\<CLSID> key.
- using (RegistryKey ClsIdKey = ClsIdRootKey.CreateSubKey(strClsId))
- {
- ClsIdKey.SetValue("", strDocString);
-
- // Create the HKEY_CLASS_ROOT\CLSID\<CLSID>\InprocServer32 key.
- using (RegistryKey InProcServerKey = ClsIdKey.CreateSubKey("InprocServer32"))
- {
- InProcServerKey.SetValue("", strMsCorEEFileName);
- InProcServerKey.SetValue("ThreadingModel", strManagedTypeThreadingModel);
- InProcServerKey.SetValue("Class", type.FullName);
- InProcServerKey.SetValue("Assembly", strAsmName);
- InProcServerKey.SetValue("RuntimeVersion", strRuntimeVersion);
- if (strAsmCodeBase != null)
- InProcServerKey.SetValue("CodeBase", strAsmCodeBase);
-
- // Create the HKEY_CLASS_ROOT\CLSID\<CLSID>\InprocServer32\<Version> subkey
- using (RegistryKey VersionSubKey = InProcServerKey.CreateSubKey(strAsmVersion))
- {
- VersionSubKey.SetValue("Class", type.FullName);
- VersionSubKey.SetValue("Assembly", strAsmName);
- VersionSubKey.SetValue("RuntimeVersion", strRuntimeVersion);
- if (strAsmCodeBase != null)
- VersionSubKey.SetValue("CodeBase", strAsmCodeBase);
- }
-
- if (strProgId != String.Empty)
- {
- // Create the HKEY_CLASS_ROOT\CLSID\<CLSID>\ProdId key.
- using (RegistryKey ProgIdKey = ClsIdKey.CreateSubKey("ProgId"))
- {
- ProgIdKey.SetValue("", strProgId);
- }
- }
- }
-
- // Create the HKEY_CLASS_ROOT\CLSID\<CLSID>\Implemented Categories\<Managed Category Guid> key.
- using (RegistryKey CategoryKey = ClsIdKey.CreateSubKey(strImplementedCategoriesSubKey))
- {
- using (RegistryKey ManagedCategoryKey = CategoryKey.CreateSubKey(strManagedCategoryGuid)) {}
- }
- }
- }
-
-
- //
- // Ensure that the managed category exists.
- //
-
- EnsureManagedCategoryExists();
- }
-
- private void RegisterComImportedType(Type type, String strAsmName, String strAsmVersion, String strAsmCodeBase, String strRuntimeVersion)
- {
- // Retrieve some information that will be used during the registration process.
- String strClsId = "{" + Marshal.GenerateGuidForType(type).ToString().ToUpper(CultureInfo.InvariantCulture) + "}";
-
- // Create the HKEY_CLASS_ROOT\CLSID key.
- using (RegistryKey ClsIdRootKey = Registry.ClassesRoot.CreateSubKey(strClsIdRootName))
- {
- // Create the HKEY_CLASS_ROOT\CLSID\<CLSID> key.
- using (RegistryKey ClsIdKey = ClsIdRootKey.CreateSubKey(strClsId))
- {
- // Create the HKEY_CLASS_ROOT\CLSID\<CLSID>\InProcServer32 key.
- using (RegistryKey InProcServerKey = ClsIdKey.CreateSubKey("InprocServer32"))
- {
- // Set the class value.
- InProcServerKey.SetValue("Class", type.FullName);
-
- // Set the assembly value.
- InProcServerKey.SetValue("Assembly", strAsmName);
-
- // Set the runtime version value.
- InProcServerKey.SetValue("RuntimeVersion", strRuntimeVersion);
-
- // Set the assembly code base value if a code base was specified.
- if (strAsmCodeBase != null)
- InProcServerKey.SetValue("CodeBase", strAsmCodeBase);
-
- // Create the HKEY_CLASS_ROOT\CLSID\<CLSID>\InprocServer32\<Version> subkey
- using (RegistryKey VersionSubKey = InProcServerKey.CreateSubKey(strAsmVersion))
- {
- VersionSubKey.SetValue("Class", type.FullName);
- VersionSubKey.SetValue("Assembly", strAsmName);
- VersionSubKey.SetValue("RuntimeVersion", strRuntimeVersion);
- if (strAsmCodeBase != null)
- VersionSubKey.SetValue("CodeBase", strAsmCodeBase);
- }
- }
- }
- }
- }
-
- private bool UnregisterValueType(Type type, String strAsmVersion)
- {
- bool bAllVersionsGone = true;
-
- // Try to open the HKEY_CLASS_ROOT\Record key.
- String strRecordId = "{" + Marshal.GenerateGuidForType(type).ToString().ToUpper(CultureInfo.InvariantCulture) + "}";
-
- using (RegistryKey RecordRootKey = Registry.ClassesRoot.OpenSubKey(strRecordRootName, true))
- {
- if (RecordRootKey != null)
- {
- // Open the HKEY_CLASS_ROOT\Record\{RecordId} key.
- using (RegistryKey RecordKey = RecordRootKey.OpenSubKey(strRecordId,true))
- {
- if (RecordKey != null)
- {
- using (RegistryKey VersionSubKey = RecordKey.OpenSubKey(strAsmVersion,true))
- {
- if (VersionSubKey != null)
- {
- // Delete the values we created.
- VersionSubKey.DeleteValue("Assembly",false);
- VersionSubKey.DeleteValue("Class",false);
- VersionSubKey.DeleteValue("CodeBase",false);
- VersionSubKey.DeleteValue("RuntimeVersion",false);
-
- // delete the version sub key if no value or subkeys under it
- if ((VersionSubKey.SubKeyCount == 0) && (VersionSubKey.ValueCount == 0))
- RecordKey.DeleteSubKey(strAsmVersion);
- }
- }
-
- // If there are sub keys left then there are versions left.
- if (RecordKey.SubKeyCount != 0)
- bAllVersionsGone = false;
-
- // If there are no other values or subkeys then we can delete the HKEY_CLASS_ROOT\Record\{RecordId}.
- if ((RecordKey.SubKeyCount == 0) && (RecordKey.ValueCount == 0))
- RecordRootKey.DeleteSubKey(strRecordId);
- }
- }
-
- // If there are no other values or subkeys then we can delete the HKEY_CLASS_ROOT\Record.
- if ((RecordRootKey.SubKeyCount == 0) && (RecordRootKey.ValueCount == 0))
- Registry.ClassesRoot.DeleteSubKey(strRecordRootName);
- }
- }
-
- return bAllVersionsGone;
- }
-
- // UnregisterManagedType
- //
- // Return :
- // true: All versions are gone.
- // false: Some versions are still left in registry
- private bool UnregisterManagedType(Type type,String strAsmVersion)
- {
- bool bAllVersionsGone = true;
-
- //
- // Create the CLSID string.
- //
-
- String strClsId = "{" + Marshal.GenerateGuidForType(type).ToString().ToUpper(CultureInfo.InvariantCulture) + "}";
- String strProgId = GetProgIdForType(type);
-
-
- //
- // Remove the entries under HKEY_CLASS_ROOT\CLSID key.
- //
-
- using (RegistryKey ClsIdRootKey = Registry.ClassesRoot.OpenSubKey(strClsIdRootName, true))
- {
- if (ClsIdRootKey != null)
- {
- //
- // Remove the entries under HKEY_CLASS_ROOT\CLSID\<CLSID> key.
- //
-
- using (RegistryKey ClsIdKey = ClsIdRootKey.OpenSubKey(strClsId, true))
- {
- if (ClsIdKey != null)
- {
- //
- // Remove the entries in the HKEY_CLASS_ROOT\CLSID\<CLSID>\InprocServer32 key.
- //
-
- using (RegistryKey InProcServerKey = ClsIdKey.OpenSubKey("InprocServer32", true))
- {
- if (InProcServerKey != null)
- {
- //
- // Remove the entries in HKEY_CLASS_ROOT\CLSID\<CLSID>\InprocServer32\<Version>
- //
-
- using (RegistryKey VersionSubKey = InProcServerKey.OpenSubKey(strAsmVersion, true))
- {
- if (VersionSubKey != null)
- {
- // Delete the values we created
- VersionSubKey.DeleteValue("Assembly",false);
- VersionSubKey.DeleteValue("Class",false);
- VersionSubKey.DeleteValue("RuntimeVersion",false);
- VersionSubKey.DeleteValue("CodeBase",false);
-
- // If there are no other values or subkeys then we can delete the VersionSubKey.
- if ((VersionSubKey.SubKeyCount == 0) && (VersionSubKey.ValueCount == 0))
- InProcServerKey.DeleteSubKey(strAsmVersion);
- }
- }
-
- // If there are sub keys left then there are versions left.
- if (InProcServerKey.SubKeyCount != 0)
- bAllVersionsGone = false;
-
- // If there are no versions left, then delete the threading model and default value.
- if (bAllVersionsGone)
- {
- InProcServerKey.DeleteValue("",false);
- InProcServerKey.DeleteValue("ThreadingModel",false);
- }
-
- InProcServerKey.DeleteValue("Assembly",false);
- InProcServerKey.DeleteValue("Class",false);
- InProcServerKey.DeleteValue("RuntimeVersion",false);
- InProcServerKey.DeleteValue("CodeBase",false);
-
- // If there are no other values or subkeys then we can delete the InProcServerKey.
- if ((InProcServerKey.SubKeyCount == 0) && (InProcServerKey.ValueCount == 0))
- ClsIdKey.DeleteSubKey("InprocServer32");
- }
- }
-
- // remove HKEY_CLASS_ROOT\CLSID\<CLSID>\ProgId
- // and HKEY_CLASS_ROOT\CLSID\<CLSID>\Implemented Category
- // only when all versions are removed
- if (bAllVersionsGone)
- {
- // Delete the value we created.
- ClsIdKey.DeleteValue("",false);
-
- if (strProgId != String.Empty)
- {
- //
- // Remove the entries in the HKEY_CLASS_ROOT\CLSID\<CLSID>\ProgId key.
- //
-
- using (RegistryKey ProgIdKey = ClsIdKey.OpenSubKey("ProgId", true))
- {
- if (ProgIdKey != null)
- {
- // Delete the value we created.
- ProgIdKey.DeleteValue("",false);
-
- // If there are no other values or subkeys then we can delete the ProgIdSubKey.
- if ((ProgIdKey.SubKeyCount == 0) && (ProgIdKey.ValueCount == 0))
- ClsIdKey.DeleteSubKey("ProgId");
- }
- }
- }
-
-
- //
- // Remove entries in the HKEY_CLASS_ROOT\CLSID\<CLSID>\Implemented Categories\<Managed Category Guid> key.
- //
-
- using (RegistryKey CategoryKey = ClsIdKey.OpenSubKey(strImplementedCategoriesSubKey, true))
- {
- if (CategoryKey != null)
- {
- using (RegistryKey ManagedCategoryKey = CategoryKey.OpenSubKey(strManagedCategoryGuid, true))
- {
- if (ManagedCategoryKey != null)
- {
- // If there are no other values or subkeys then we can delete the ManagedCategoryKey.
- if ((ManagedCategoryKey.SubKeyCount == 0) && (ManagedCategoryKey.ValueCount == 0))
- CategoryKey.DeleteSubKey(strManagedCategoryGuid);
- }
- }
-
- // If there are no other values or subkeys then we can delete the CategoryKey.
- if ((CategoryKey.SubKeyCount == 0) && (CategoryKey.ValueCount == 0))
- ClsIdKey.DeleteSubKey(strImplementedCategoriesSubKey);
- }
- }
- }
-
- // If there are no other values or subkeys then we can delete the ClsIdKey.
- if ((ClsIdKey.SubKeyCount == 0) && (ClsIdKey.ValueCount == 0))
- ClsIdRootKey.DeleteSubKey(strClsId);
- }
- }
-
- // If there are no other values or subkeys then we can delete the CLSID key.
- if ((ClsIdRootKey.SubKeyCount == 0) && (ClsIdRootKey.ValueCount == 0))
- Registry.ClassesRoot.DeleteSubKey(strClsIdRootName);
- }
-
-
- //
- // Remove the entries under HKEY_CLASS_ROOT\<wzProgId> key.
- //
-
- if (bAllVersionsGone)
- {
- if (strProgId != String.Empty)
- {
- using (RegistryKey TypeNameKey = Registry.ClassesRoot.OpenSubKey(strProgId, true))
- {
- if (TypeNameKey != null)
- {
- // Delete the values we created.
- TypeNameKey.DeleteValue("",false);
-
-
- //
- // Remove the entries in the HKEY_CLASS_ROOT\<wzProgId>\CLSID key.
- //
-
- using (RegistryKey ProgIdClsIdKey = TypeNameKey.OpenSubKey("CLSID", true))
- {
- if (ProgIdClsIdKey != null)
- {
- // Delete the values we created.
- ProgIdClsIdKey.DeleteValue("",false);
-
- // If there are no other values or subkeys then we can delete the ProgIdClsIdKey.
- if ((ProgIdClsIdKey.SubKeyCount == 0) && (ProgIdClsIdKey.ValueCount == 0))
- TypeNameKey.DeleteSubKey("CLSID");
- }
- }
-
- // If there are no other values or subkeys then we can delete the TypeNameKey.
- if ((TypeNameKey.SubKeyCount == 0) && (TypeNameKey.ValueCount == 0))
- Registry.ClassesRoot.DeleteSubKey(strProgId);
- }
- }
- }
- }
- }
-
- return bAllVersionsGone;
- }
-
- // UnregisterComImportedType
- // Return:
- // true: All version information are gone.
- // false: There are still some version left in registry
- private bool UnregisterComImportedType(Type type, String strAsmVersion)
- {
- bool bAllVersionsGone = true;
-
- String strClsId = "{" + Marshal.GenerateGuidForType(type).ToString().ToUpper(CultureInfo.InvariantCulture) + "}";
-
- // Try to open the HKEY_CLASS_ROOT\CLSID key.
- using (RegistryKey ClsIdRootKey = Registry.ClassesRoot.OpenSubKey(strClsIdRootName, true))
- {
- if (ClsIdRootKey != null)
- {
- // Try to open the HKEY_CLASS_ROOT\CLSID\<CLSID> key.
- using (RegistryKey ClsIdKey = ClsIdRootKey.OpenSubKey(strClsId, true))
- {
- if (ClsIdKey != null)
- {
- // Try to open the HKEY_CLASS_ROOT\CLSID\<CLSID>\InProcServer32 key.
- using (RegistryKey InProcServerKey = ClsIdKey.OpenSubKey("InprocServer32", true))
- {
- if (InProcServerKey != null)
- {
- // Delete the values we created.
- InProcServerKey.DeleteValue("Assembly",false);
- InProcServerKey.DeleteValue("Class",false);
- InProcServerKey.DeleteValue("RuntimeVersion",false);
- InProcServerKey.DeleteValue("CodeBase",false);
-
- // Try to open the entries in HKEY_CLASS_ROOT\CLSID\<CLSID>\InProcServer32\<Version>
- using (RegistryKey VersionSubKey = InProcServerKey.OpenSubKey(strAsmVersion,true))
- {
- if (VersionSubKey != null)
- {
- // Delete the value we created
- VersionSubKey.DeleteValue("Assembly",false);
- VersionSubKey.DeleteValue("Class",false);
- VersionSubKey.DeleteValue("RuntimeVersion",false);
- VersionSubKey.DeleteValue("CodeBase",false);
-
- // If there are no other values or subkeys then we can delete the VersionSubKey
- if ((VersionSubKey.SubKeyCount == 0) && (VersionSubKey.ValueCount == 0))
- InProcServerKey.DeleteSubKey(strAsmVersion);
- }
- }
-
- // If there are sub keys left then there are versions left.
- if (InProcServerKey.SubKeyCount != 0)
- bAllVersionsGone = false;
-
- // If there are no other values or subkeys then we can delete the InProcServerKey.
- if ((InProcServerKey.SubKeyCount == 0) && (InProcServerKey.ValueCount == 0))
- ClsIdKey.DeleteSubKey("InprocServer32");
- }
- }
-
- // If there are no other values or subkeys then we can delete the ClsIdKey.
- if ((ClsIdKey.SubKeyCount == 0) && (ClsIdKey.ValueCount == 0))
- ClsIdRootKey.DeleteSubKey(strClsId);
- }
- }
-
- // If there are no other values or subkeys then we can delete the CLSID key.
- if ((ClsIdRootKey.SubKeyCount == 0) && (ClsIdRootKey.ValueCount == 0))
- Registry.ClassesRoot.DeleteSubKey(strClsIdRootName);
- }
- }
-
- return bAllVersionsGone;
- }
-
- private void RegisterPrimaryInteropAssembly(RuntimeAssembly assembly, String strAsmCodeBase, PrimaryInteropAssemblyAttribute attr)
- {
- // Validate that the PIA has a strong name.
- if (assembly.GetPublicKey().Length == 0)
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_PIAMustBeStrongNamed"));
-
- String strTlbId = "{" + Marshal.GetTypeLibGuidForAssembly(assembly).ToString().ToUpper(CultureInfo.InvariantCulture) + "}";
- String strVersion = attr.MajorVersion.ToString("x", CultureInfo.InvariantCulture) + "." + attr.MinorVersion.ToString("x", CultureInfo.InvariantCulture);
-
- // Create the HKEY_CLASS_ROOT\TypeLib key.
- using (RegistryKey TypeLibRootKey = Registry.ClassesRoot.CreateSubKey(strTlbRootName))
- {
- // Create the HKEY_CLASS_ROOT\TypeLib\<TLBID> key.
- using (RegistryKey TypeLibKey = TypeLibRootKey.CreateSubKey(strTlbId))
- {
- // Create the HKEY_CLASS_ROOT\TypeLib\<TLBID>\<Major.Minor> key.
- using (RegistryKey VersionSubKey = TypeLibKey.CreateSubKey(strVersion))
- {
- // Create the HKEY_CLASS_ROOT\TypeLib\<TLBID>\PrimaryInteropAssembly key.
- VersionSubKey.SetValue("PrimaryInteropAssemblyName", assembly.FullName);
- if (strAsmCodeBase != null)
- VersionSubKey.SetValue("PrimaryInteropAssemblyCodeBase", strAsmCodeBase);
- }
- }
- }
- }
-
- private void UnregisterPrimaryInteropAssembly(Assembly assembly, PrimaryInteropAssemblyAttribute attr)
- {
- String strTlbId = "{" + Marshal.GetTypeLibGuidForAssembly(assembly).ToString().ToUpper(CultureInfo.InvariantCulture) + "}";
- String strVersion = attr.MajorVersion.ToString("x", CultureInfo.InvariantCulture) + "." + attr.MinorVersion.ToString("x", CultureInfo.InvariantCulture);
-
- // Try to open the HKEY_CLASS_ROOT\TypeLib key.
- using (RegistryKey TypeLibRootKey = Registry.ClassesRoot.OpenSubKey(strTlbRootName, true))
- {
- if (TypeLibRootKey != null)
- {
- // Try to open the HKEY_CLASS_ROOT\TypeLib\<TLBID> key.
- using (RegistryKey TypeLibKey = TypeLibRootKey.OpenSubKey(strTlbId, true))
- {
- if (TypeLibKey != null)
- {
- // Try to open the HKEY_CLASS_ROOT\TypeLib<TLBID>\<Major.Minor> key.
- using (RegistryKey VersionSubKey = TypeLibKey.OpenSubKey(strVersion, true))
- {
- if (VersionSubKey != null)
- {
- // Delete the values we created.
- VersionSubKey.DeleteValue("PrimaryInteropAssemblyName",false);
- VersionSubKey.DeleteValue("PrimaryInteropAssemblyCodeBase",false);
-
- // If there are no other values or subkeys then we can delete the VersionKey.
- if ((VersionSubKey.SubKeyCount == 0) && (VersionSubKey.ValueCount == 0))
- TypeLibKey.DeleteSubKey(strVersion);
- }
- }
-
- // If there are no other values or subkeys then we can delete the TypeLibKey.
- if ((TypeLibKey.SubKeyCount == 0) && (TypeLibKey.ValueCount == 0))
- TypeLibRootKey.DeleteSubKey(strTlbId);
- }
- }
-
- // If there are no other values or subkeys then we can delete the TypeLib key.
- if ((TypeLibRootKey.SubKeyCount == 0) && (TypeLibRootKey.ValueCount == 0))
- Registry.ClassesRoot.DeleteSubKey(strTlbRootName);
- }
- }
- }
-
- private void EnsureManagedCategoryExists()
- {
- if (!ManagedCategoryExists())
- {
- // Create the HKEY_CLASS_ROOT\Component Category key.
- using (RegistryKey ComponentCategoryKey = Registry.ClassesRoot.CreateSubKey(strComponentCategorySubKey))
- {
- // Create the HKEY_CLASS_ROOT\Component Category\<Managed Category Guid> key.
- using (RegistryKey ManagedCategoryKey = ComponentCategoryKey.CreateSubKey(strManagedCategoryGuid))
- {
- ManagedCategoryKey.SetValue("0", strManagedCategoryDescription);
- }
- }
- }
- }
-
- private static bool ManagedCategoryExists()
- {
- using (RegistryKey componentCategoryKey = Registry.ClassesRoot.OpenSubKey(strComponentCategorySubKey,
- false))
- {
- if (componentCategoryKey == null)
- return false;
- using (RegistryKey managedCategoryKey = componentCategoryKey.OpenSubKey(strManagedCategoryGuid,
- false))
- {
- if (managedCategoryKey == null)
- return false;
- object value = managedCategoryKey.GetValue("0");
- if (value == null || value.GetType() != typeof(string))
- return false;
- string stringValue = (string)value;
- if (stringValue != strManagedCategoryDescription)
- return false;
- }
- }
-
- return true;
- }
-
- private void CallUserDefinedRegistrationMethod(Type type, bool bRegister)
- {
- bool bFunctionCalled = false;
-
- // Retrieve the attribute type to use to determine if a function is the requested user defined
- // registration function.
- Type RegFuncAttrType = null;
- if(bRegister)
- RegFuncAttrType = typeof(ComRegisterFunctionAttribute);
- else
- RegFuncAttrType = typeof(ComUnregisterFunctionAttribute);
-
- for(Type currType = type; !bFunctionCalled && currType != null; currType = currType.BaseType)
- {
- // Retrieve all the methods.
- MethodInfo[] aMethods = currType.GetMethods(BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic|BindingFlags.Static);
- int NumMethods = aMethods.Length;
-
- // Go through all the methods and check for the ComRegisterMethod custom attribute.
- for(int cMethods = 0;cMethods < NumMethods;cMethods++)
- {
- MethodInfo CurrentMethod = aMethods[cMethods];
-
- // Check to see if the method has the custom attribute.
- if(CurrentMethod.GetCustomAttributes(RegFuncAttrType, true).Length != 0)
- {
- // Check to see if the method is static before we call it.
- if(!CurrentMethod.IsStatic)
- {
- if(bRegister)
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NonStaticComRegFunction",CurrentMethod.Name,currType.Name));
- else
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NonStaticComUnRegFunction",CurrentMethod.Name,currType.Name));
- }
-
- // Finally check that the signature is string ret void.
- ParameterInfo[] aParams = CurrentMethod.GetParameters();
- if (CurrentMethod.ReturnType != typeof(void) ||
- aParams == null ||
- aParams.Length != 1 ||
- (aParams[0].ParameterType != typeof(String) && aParams[0].ParameterType != typeof(Type)))
- {
- if(bRegister)
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_InvalidComRegFunctionSig",CurrentMethod.Name,currType.Name));
- else
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_InvalidComUnRegFunctionSig",CurrentMethod.Name,currType.Name));
- }
-
- // There can only be one register and one unregister function per type.
- if(bFunctionCalled)
- {
- if(bRegister)
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_MultipleComRegFunctions",currType.Name));
- else
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_MultipleComUnRegFunctions",currType.Name));
- }
-
- // The function is valid so set up the arguments to call it.
- Object[] objs = new Object[1];
- if(aParams[0].ParameterType == typeof(String))
- {
- // We are dealing with the string overload of the function.
- objs[0] = "HKEY_CLASSES_ROOT\\CLSID\\{" + Marshal.GenerateGuidForType(type).ToString().ToUpper(CultureInfo.InvariantCulture) + "}";
- }
- else
- {
- // We are dealing with the type overload of the function.
- objs[0] = type;
- }
-
- // Invoke the COM register function.
- CurrentMethod.Invoke(null, objs);
-
- // Mark the function as having been called.
- bFunctionCalled = true;
- }
- }
- }
- }
-
- private Type GetBaseComImportType(Type type)
- {
- for (; type != null && !type.IsImport; type = type.BaseType);
- return type;
- }
-
- private bool IsRegisteredAsValueType(Type type)
- {
- if (!type.IsValueType)
- return false;
-
- return true;
- }
-
- #endregion
-
-
- #region FCalls and DllImports
-
-#if FEATURE_COMINTEROP_MANAGED_ACTIVATION
- // GUID versioning can be controlled by using the GuidAttribute or
- // letting the runtime generate it based on type and assembly strong name.
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- private static extern void RegisterTypeForComClientsNative(Type type,ref Guid g);
-
- // GUID versioning can be controlled by using the GuidAttribute or
- // letting the runtime generate it based on type and assembly strong name.
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- private static extern int RegisterTypeForComClientsExNative(Type t, RegistrationClassContext clsContext, RegistrationConnectionType flags);
-#endif // FEATURE_COMINTEROP_MANAGED_ACTIVATION
-
- [DllImport(Win32Native.OLE32,CharSet=CharSet.Auto,PreserveSig=false)]
- private static extern void CoRevokeClassObject(int cookie);
- #endregion
- }
-}
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-namespace System.Runtime.InteropServices.TCEAdapterGen {
-
- using System;
- using System.Reflection;
- using System.Collections;
-
- internal class EventItfInfo
- {
- public EventItfInfo(String strEventItfName,
- String strSrcItfName,
- String strEventProviderName,
- RuntimeAssembly asmImport,
- RuntimeAssembly asmSrcItf)
- {
- m_strEventItfName = strEventItfName;
- m_strSrcItfName = strSrcItfName;
- m_strEventProviderName = strEventProviderName;
- m_asmImport = asmImport;
- m_asmSrcItf = asmSrcItf;
- }
-
- public Type GetEventItfType()
- {
- Type t = m_asmImport.GetType(m_strEventItfName, true, false);
- if (t != null && !t.IsVisible)
- t = null;
- return t;
- }
-
- public Type GetSrcItfType()
- {
- Type t = m_asmSrcItf.GetType(m_strSrcItfName, true, false);
- if (t != null && !t.IsVisible)
- t = null;
- return t;
- }
-
- public String GetEventProviderName()
- {
- return m_strEventProviderName;
- }
-
- private String m_strEventItfName;
- private String m_strSrcItfName;
- private String m_strEventProviderName;
- private RuntimeAssembly m_asmImport;
- private RuntimeAssembly m_asmSrcItf;
- }
-}
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-namespace System.Runtime.InteropServices.TCEAdapterGen {
- using System.Runtime.InteropServices.ComTypes;
- using ubyte = System.Byte;
- using System;
- using System.Reflection;
- using System.Reflection.Emit;
- using System.Collections;
- using System.Threading;
- using System.Diagnostics;
- using System.Diagnostics.Contracts;
-
- internal class EventProviderWriter
- {
- private const BindingFlags DefaultLookup = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public;
-
- private readonly Type[] MonitorEnterParamTypes = new Type[] { typeof(Object), Type.GetType("System.Boolean&") };
-
- public EventProviderWriter( ModuleBuilder OutputModule, String strDestTypeName, Type EventItfType, Type SrcItfType, Type SinkHelperType )
- {
- m_OutputModule = OutputModule;
- m_strDestTypeName = strDestTypeName;
- m_EventItfType = EventItfType;
- m_SrcItfType = SrcItfType;
- m_SinkHelperType = SinkHelperType;
- }
-
- public Type Perform()
- {
- // Create the event provider class.
- TypeBuilder OutputTypeBuilder = m_OutputModule.DefineType(
- m_strDestTypeName,
- TypeAttributes.Sealed | TypeAttributes.NotPublic,
- typeof(Object),
- new Type[]{m_EventItfType, typeof(IDisposable)}
- );
-
- // Create the event source field.
- FieldBuilder fbCPC = OutputTypeBuilder.DefineField(
- "m_ConnectionPointContainer",
- typeof(IConnectionPointContainer),
- FieldAttributes.Private
- );
-
- // Create array of event sink helpers.
- FieldBuilder fbSinkHelper = OutputTypeBuilder.DefineField(
- "m_aEventSinkHelpers",
- typeof(ArrayList),
- FieldAttributes.Private
- );
-
- // Define the connection point field.
- FieldBuilder fbEventCP = OutputTypeBuilder.DefineField(
- "m_ConnectionPoint",
- typeof(IConnectionPoint),
- FieldAttributes.Private
- );
-
- // Define the InitXXX method.
- MethodBuilder InitSrcItfMethodBuilder =
- DefineInitSrcItfMethod( OutputTypeBuilder, m_SrcItfType, fbSinkHelper, fbEventCP, fbCPC );
-
- // Process all the methods in the event interface.
- MethodInfo[] aMethods = TCEAdapterGenerator.GetNonPropertyMethods(m_SrcItfType);
- for ( int cMethods = 0; cMethods < aMethods.Length; cMethods++ )
- {
- if ( m_SrcItfType == aMethods[cMethods].DeclaringType )
- {
- // Define the add_XXX method.
- MethodBuilder AddEventMethodBuilder = DefineAddEventMethod(
- OutputTypeBuilder, aMethods[cMethods], m_SinkHelperType, fbSinkHelper, fbEventCP, InitSrcItfMethodBuilder );
-
- // Define the remove_XXX method.
- MethodBuilder RemoveEventMethodBuilder = DefineRemoveEventMethod(
- OutputTypeBuilder, aMethods[cMethods], m_SinkHelperType, fbSinkHelper, fbEventCP );
- }
- }
-
- // Define the constructor.
- DefineConstructor( OutputTypeBuilder, fbCPC );
-
- // Define the finalize method.
- MethodBuilder FinalizeMethod = DefineFinalizeMethod( OutputTypeBuilder, m_SinkHelperType, fbSinkHelper, fbEventCP );
-
- // Define the Dispose method.
- DefineDisposeMethod( OutputTypeBuilder, FinalizeMethod);
-
- return OutputTypeBuilder.CreateType();
- }
-
- private MethodBuilder DefineAddEventMethod( TypeBuilder OutputTypeBuilder, MethodInfo SrcItfMethod, Type SinkHelperClass, FieldBuilder fbSinkHelperArray, FieldBuilder fbEventCP, MethodBuilder mbInitSrcItf )
- {
- Type[] aParamTypes;
-
- // Find the delegate on the event sink helper.
- FieldInfo DelegateField = SinkHelperClass.GetField( "m_" + SrcItfMethod.Name + "Delegate" );
- Debug.Assert(DelegateField != null, "Unable to find the field m_" + SrcItfMethod.Name + "Delegate on the sink helper");
-
- // Find the cookie on the event sink helper.
- FieldInfo CookieField = SinkHelperClass.GetField( "m_dwCookie" );
- Debug.Assert(CookieField != null, "Unable to find the field m_dwCookie on the sink helper");
-
- // Retrieve the sink helper's constructor.
- ConstructorInfo SinkHelperCons = SinkHelperClass.GetConstructor(EventProviderWriter.DefaultLookup | BindingFlags.NonPublic, null, Array.Empty<Type>(), null );
- Debug.Assert(SinkHelperCons != null, "Unable to find the constructor for the sink helper");
-
- // Retrieve the IConnectionPoint.Advise method.
- MethodInfo CPAdviseMethod = typeof(IConnectionPoint).GetMethod( "Advise" );
- Debug.Assert(CPAdviseMethod != null, "Unable to find the method ConnectionPoint.Advise");
-
- // Retrieve the ArrayList.Add method.
- aParamTypes = new Type[1];
- aParamTypes[0] = typeof(Object);
- MethodInfo ArrayListAddMethod = typeof(ArrayList).GetMethod( "Add", aParamTypes, null );
- Debug.Assert(ArrayListAddMethod != null, "Unable to find the method ArrayList.Add");
-
- // Retrieve the Monitor.Enter() method.
- MethodInfo MonitorEnterMethod = typeof(Monitor).GetMethod( "Enter", MonitorEnterParamTypes, null );
- Debug.Assert(MonitorEnterMethod != null, "Unable to find the method Monitor.Enter()");
-
- // Retrieve the Monitor.Exit() method.
- aParamTypes[0] = typeof(Object);
- MethodInfo MonitorExitMethod = typeof(Monitor).GetMethod( "Exit", aParamTypes, null );
- Debug.Assert(MonitorExitMethod != null, "Unable to find the method Monitor.Exit()");
-
- // Define the add_XXX method.
- Type[] parameterTypes;
- parameterTypes = new Type[1];
- parameterTypes[0] = DelegateField.FieldType;
- MethodBuilder Meth = OutputTypeBuilder.DefineMethod(
- "add_" + SrcItfMethod.Name,
- MethodAttributes.Public | MethodAttributes.Virtual,
- null,
- parameterTypes );
-
- ILGenerator il = Meth.GetILGenerator();
-
- // Define a label for the m_IFooEventsCP comparision.
- Label EventCPNonNullLabel = il.DefineLabel();
-
- // Declare the local variables.
- LocalBuilder ltSinkHelper = il.DeclareLocal( SinkHelperClass );
- LocalBuilder ltCookie = il.DeclareLocal( typeof(Int32) );
- LocalBuilder ltLockTaken = il.DeclareLocal( typeof(bool) );
-
- // Generate the following code:
- // try {
- il.BeginExceptionBlock();
-
- // Generate the following code:
- // Monitor.Enter(this, ref lockTaken);
- il.Emit(OpCodes.Ldarg, (short)0);
- il.Emit(OpCodes.Ldloca_S, ltLockTaken);
- il.Emit(OpCodes.Call, MonitorEnterMethod);
-
- // Generate the following code:
- // if ( m_IFooEventsCP != null ) goto EventCPNonNullLabel;
- il.Emit( OpCodes.Ldarg, (short)0 );
- il.Emit( OpCodes.Ldfld, fbEventCP );
- il.Emit( OpCodes.Brtrue, EventCPNonNullLabel );
-
- // Generate the following code:
- // InitIFooEvents();
- il.Emit( OpCodes.Ldarg, (short)0 );
- il.Emit( OpCodes.Call, mbInitSrcItf );
-
- // Mark this as label to jump to if the CP is not null.
- il.MarkLabel( EventCPNonNullLabel );
-
- // Generate the following code:
- // IFooEvents_SinkHelper SinkHelper = new IFooEvents_SinkHelper;
- il.Emit( OpCodes.Newobj, SinkHelperCons );
- il.Emit( OpCodes.Stloc, ltSinkHelper );
-
- // Generate the following code:
- // dwCookie = 0;
- il.Emit( OpCodes.Ldc_I4_0 );
- il.Emit( OpCodes.Stloc, ltCookie );
-
- // Generate the following code:
- // m_IFooEventsCP.Advise( SinkHelper, dwCookie );
- il.Emit( OpCodes.Ldarg, (short)0 );
- il.Emit( OpCodes.Ldfld, fbEventCP );
- il.Emit( OpCodes.Ldloc, ltSinkHelper );
- il.Emit( OpCodes.Castclass, typeof(Object) );
- il.Emit( OpCodes.Ldloca, ltCookie );
- il.Emit( OpCodes.Callvirt, CPAdviseMethod );
-
- // Generate the following code:
- // SinkHelper.m_dwCookie = dwCookie;
- il.Emit( OpCodes.Ldloc, ltSinkHelper );
- il.Emit( OpCodes.Ldloc, ltCookie );
- il.Emit( OpCodes.Stfld, CookieField );
-
- // Generate the following code:
- // SinkHelper.m_FooDelegate = d;
- il.Emit( OpCodes.Ldloc, ltSinkHelper );
- il.Emit( OpCodes.Ldarg, (short)1 );
- il.Emit( OpCodes.Stfld, DelegateField );
-
- // Generate the following code:
- // m_aIFooEventsHelpers.Add( SinkHelper );
- il.Emit( OpCodes.Ldarg, (short)0 );
- il.Emit( OpCodes.Ldfld, fbSinkHelperArray );
- il.Emit( OpCodes.Ldloc, ltSinkHelper );
- il.Emit( OpCodes.Castclass, typeof(Object) );
- il.Emit( OpCodes.Callvirt, ArrayListAddMethod );
- il.Emit( OpCodes.Pop );
-
- // Generate the following code:
- // } finally {
- il.BeginFinallyBlock();
-
- // Generate the following code:
- // if (lockTaken)
- // Monitor.Exit(this);
- Label skipExit = il.DefineLabel();
- il.Emit( OpCodes.Ldloc, ltLockTaken );
- il.Emit( OpCodes.Brfalse_S, skipExit );
- il.Emit( OpCodes.Ldarg, (short)0 );
- il.Emit( OpCodes.Call, MonitorExitMethod );
- il.MarkLabel(skipExit);
-
- // Generate the following code:
- // }
- il.EndExceptionBlock();
-
- // Generate the return opcode.
- il.Emit( OpCodes.Ret );
-
- return Meth;
- }
-
- private MethodBuilder DefineRemoveEventMethod( TypeBuilder OutputTypeBuilder, MethodInfo SrcItfMethod, Type SinkHelperClass, FieldBuilder fbSinkHelperArray, FieldBuilder fbEventCP )
- {
- Type[] aParamTypes;
-
- // Find the delegate on the event sink helper.
- FieldInfo DelegateField = SinkHelperClass.GetField( "m_" + SrcItfMethod.Name + "Delegate" );
- Debug.Assert(DelegateField != null, "Unable to find the field m_" + SrcItfMethod.Name + "Delegate on the sink helper");
-
- // Find the cookie on the event sink helper.
- FieldInfo CookieField = SinkHelperClass.GetField( "m_dwCookie" );
- Debug.Assert(CookieField != null, "Unable to find the field m_dwCookie on the sink helper");
-
- // Retrieve the ArrayList.RemoveAt method.
- aParamTypes = new Type[1];
- aParamTypes[0] = typeof(Int32);
- MethodInfo ArrayListRemoveMethod = typeof(ArrayList).GetMethod( "RemoveAt", aParamTypes, null );
- Debug.Assert(ArrayListRemoveMethod != null, "Unable to find the method ArrayList.RemoveAt()");
-
- // Retrieve the ArrayList.Item property get method.
- PropertyInfo ArrayListItemProperty = typeof(ArrayList).GetProperty( "Item" );
- Debug.Assert(ArrayListItemProperty != null, "Unable to find the property ArrayList.Item");
- MethodInfo ArrayListItemGetMethod = ArrayListItemProperty.GetGetMethod();
- Debug.Assert(ArrayListItemGetMethod != null, "Unable to find the get method for property ArrayList.Item");
-
- // Retrieve the ArrayList.Count property get method.
- PropertyInfo ArrayListSizeProperty = typeof(ArrayList).GetProperty( "Count" );
- Debug.Assert(ArrayListSizeProperty != null, "Unable to find the property ArrayList.Count");
- MethodInfo ArrayListSizeGetMethod = ArrayListSizeProperty.GetGetMethod();
- Debug.Assert(ArrayListSizeGetMethod != null, "Unable to find the get method for property ArrayList.Count");
-
- // Retrieve the Delegate.Equals() method.
- aParamTypes[0] = typeof(Delegate);
- MethodInfo DelegateEqualsMethod = typeof(Delegate).GetMethod( "Equals", aParamTypes, null );
- Debug.Assert(DelegateEqualsMethod != null, "Unable to find the method Delegate.Equlals()");
-
- // Retrieve the Monitor.Enter() method.
- MethodInfo MonitorEnterMethod = typeof(Monitor).GetMethod("Enter", MonitorEnterParamTypes, null);
- Debug.Assert(MonitorEnterMethod != null, "Unable to find the method Monitor.Enter()");
-
- // Retrieve the Monitor.Exit() method.
- aParamTypes[0] = typeof(Object);
- MethodInfo MonitorExitMethod = typeof(Monitor).GetMethod( "Exit", aParamTypes, null );
- Debug.Assert(MonitorExitMethod != null, "Unable to find the method Monitor.Exit()");
-
- // Retrieve the ConnectionPoint.Unadvise() method.
- MethodInfo CPUnadviseMethod = typeof(IConnectionPoint).GetMethod( "Unadvise" );
- Debug.Assert(CPUnadviseMethod != null, "Unable to find the method ConnectionPoint.Unadvise()");
-
- // Retrieve the Marshal.ReleaseComObject() method.
- MethodInfo ReleaseComObjectMethod = typeof(Marshal).GetMethod( "ReleaseComObject" );
- Debug.Assert(ReleaseComObjectMethod != null, "Unable to find the method Marshal.ReleaseComObject()");
-
- // Define the remove_XXX method.
- Type[] parameterTypes;
- parameterTypes = new Type[1];
- parameterTypes[0] = DelegateField.FieldType;
- MethodBuilder Meth = OutputTypeBuilder.DefineMethod(
- "remove_" + SrcItfMethod.Name,
- MethodAttributes.Public | MethodAttributes.Virtual,
- null,
- parameterTypes );
-
- ILGenerator il = Meth.GetILGenerator();
-
- // Declare the local variables.
- LocalBuilder ltNumSinkHelpers = il.DeclareLocal( typeof(Int32) );
- LocalBuilder ltSinkHelperCounter = il.DeclareLocal( typeof(Int32) );
- LocalBuilder ltCurrSinkHelper = il.DeclareLocal( SinkHelperClass );
- LocalBuilder ltLockTaken = il.DeclareLocal(typeof(bool));
-
- // Generate the labels for the for loop.
- Label ForBeginLabel = il.DefineLabel();
- Label ForEndLabel = il.DefineLabel();
- Label FalseIfLabel = il.DefineLabel();
- Label MonitorExitLabel = il.DefineLabel();
-
- // Generate the following code:
- // try {
- il.BeginExceptionBlock();
-
- // Generate the following code:
- // Monitor.Enter(this, ref lockTaken);
- il.Emit(OpCodes.Ldarg, (short)0);
- il.Emit(OpCodes.Ldloca_S, ltLockTaken);
- il.Emit(OpCodes.Call, MonitorEnterMethod);
-
- // Generate the following code:
- // if ( m_aIFooEventsHelpers == null ) goto ForEndLabel;
- il.Emit( OpCodes.Ldarg, (short)0 );
- il.Emit( OpCodes.Ldfld, fbSinkHelperArray );
- il.Emit( OpCodes.Brfalse, ForEndLabel );
-
- // Generate the following code:
- // int NumEventHelpers = m_aIFooEventsHelpers.Count;
- // int cEventHelpers = 0;
- il.Emit( OpCodes.Ldarg, (short)0 );
- il.Emit( OpCodes.Ldfld, fbSinkHelperArray );
- il.Emit( OpCodes.Callvirt, ArrayListSizeGetMethod );
- il.Emit( OpCodes.Stloc, ltNumSinkHelpers );
- il.Emit( OpCodes.Ldc_I4, 0 );
- il.Emit( OpCodes.Stloc, ltSinkHelperCounter );
-
- // Generate the following code:
- // if ( 0 >= NumEventHelpers ) goto ForEndLabel;
- il.Emit( OpCodes.Ldc_I4, 0 );
- il.Emit( OpCodes.Ldloc, ltNumSinkHelpers );
- il.Emit( OpCodes.Bge, ForEndLabel );
-
- // Mark this as the beginning of the for loop's body.
- il.MarkLabel( ForBeginLabel );
-
- // Generate the following code:
- // CurrentHelper = (IFooEvents_SinkHelper)m_aIFooEventsHelpers.Get( cEventHelpers );
- il.Emit( OpCodes.Ldarg, (short)0 );
- il.Emit( OpCodes.Ldfld, fbSinkHelperArray );
- il.Emit( OpCodes.Ldloc, ltSinkHelperCounter );
- il.Emit( OpCodes.Callvirt, ArrayListItemGetMethod );
- il.Emit( OpCodes.Castclass, SinkHelperClass );
- il.Emit( OpCodes.Stloc, ltCurrSinkHelper );
-
- // Generate the following code:
- // if ( CurrentHelper.m_FooDelegate )
- il.Emit( OpCodes.Ldloc, ltCurrSinkHelper );
- il.Emit( OpCodes.Ldfld, DelegateField );
- il.Emit( OpCodes.Ldnull );
- il.Emit( OpCodes.Beq, FalseIfLabel );
-
- // Generate the following code:
- // if ( CurrentHelper.m_FooDelegate.Equals( d ) )
- il.Emit( OpCodes.Ldloc, ltCurrSinkHelper );
- il.Emit( OpCodes.Ldfld, DelegateField );
- il.Emit( OpCodes.Ldarg, (short)1 );
- il.Emit( OpCodes.Castclass, typeof(Object) );
- il.Emit( OpCodes.Callvirt, DelegateEqualsMethod );
- il.Emit( OpCodes.Ldc_I4, 0xff );
- il.Emit( OpCodes.And );
- il.Emit( OpCodes.Ldc_I4, 0 );
- il.Emit( OpCodes.Beq, FalseIfLabel );
-
- // Generate the following code:
- // m_aIFooEventsHelpers.RemoveAt( cEventHelpers );
- il.Emit( OpCodes.Ldarg, (short)0 );
- il.Emit( OpCodes.Ldfld, fbSinkHelperArray );
- il.Emit( OpCodes.Ldloc, ltSinkHelperCounter );
- il.Emit( OpCodes.Callvirt, ArrayListRemoveMethod );
-
- // Generate the following code:
- // m_IFooEventsCP.Unadvise( CurrentHelper.m_dwCookie );
- il.Emit( OpCodes.Ldarg, (short)0 );
- il.Emit( OpCodes.Ldfld, fbEventCP );
- il.Emit( OpCodes.Ldloc, ltCurrSinkHelper );
- il.Emit( OpCodes.Ldfld, CookieField );
- il.Emit( OpCodes.Callvirt, CPUnadviseMethod );
-
- // Generate the following code:
- // if ( NumEventHelpers > 1) break;
- il.Emit( OpCodes.Ldloc, ltNumSinkHelpers );
- il.Emit( OpCodes.Ldc_I4, 1 );
- il.Emit( OpCodes.Bgt, ForEndLabel );
-
- // Generate the following code:
- // Marshal.ReleaseComObject(m_IFooEventsCP);
- il.Emit( OpCodes.Ldarg, (short)0 );
- il.Emit( OpCodes.Ldfld, fbEventCP );
- il.Emit( OpCodes.Call, ReleaseComObjectMethod );
- il.Emit( OpCodes.Pop );
-
- // Generate the following code:
- // m_IFooEventsCP = null;
- il.Emit( OpCodes.Ldarg, (short)0 );
- il.Emit( OpCodes.Ldnull );
- il.Emit( OpCodes.Stfld, fbEventCP );
-
- // Generate the following code:
- // m_aIFooEventsHelpers = null;
- il.Emit( OpCodes.Ldarg, (short)0 );
- il.Emit( OpCodes.Ldnull );
- il.Emit( OpCodes.Stfld, fbSinkHelperArray );
-
- // Generate the following code:
- // break;
- il.Emit( OpCodes.Br, ForEndLabel );
-
- // Mark this as the label to jump to when the if statement is false.
- il.MarkLabel( FalseIfLabel );
-
- // Generate the following code:
- // cEventHelpers++;
- il.Emit( OpCodes.Ldloc, ltSinkHelperCounter );
- il.Emit( OpCodes.Ldc_I4, 1 );
- il.Emit( OpCodes.Add );
- il.Emit( OpCodes.Stloc, ltSinkHelperCounter );
-
- // Generate the following code:
- // if ( cEventHelpers < NumEventHelpers ) goto ForBeginLabel;
- il.Emit( OpCodes.Ldloc, ltSinkHelperCounter );
- il.Emit( OpCodes.Ldloc, ltNumSinkHelpers );
- il.Emit( OpCodes.Blt, ForBeginLabel );
-
- // Mark this as the end of the for loop's body.
- il.MarkLabel( ForEndLabel );
-
- // Generate the following code:
- // } finally {
- il.BeginFinallyBlock();
-
- // Generate the following code:
- // if (lockTaken)
- // Monitor.Exit(this);
- Label skipExit = il.DefineLabel();
- il.Emit(OpCodes.Ldloc, ltLockTaken);
- il.Emit(OpCodes.Brfalse_S, skipExit);
- il.Emit(OpCodes.Ldarg, (short)0);
- il.Emit(OpCodes.Call, MonitorExitMethod);
- il.MarkLabel(skipExit);
-
- // Generate the following code:
- // }
- il.EndExceptionBlock();
-
- // Generate the return opcode.
- il.Emit( OpCodes.Ret );
-
- return Meth;
- }
-
- private MethodBuilder DefineInitSrcItfMethod( TypeBuilder OutputTypeBuilder, Type SourceInterface, FieldBuilder fbSinkHelperArray, FieldBuilder fbEventCP, FieldBuilder fbCPC )
- {
- // Retrieve the constructor info for the array list's default constructor.
- ConstructorInfo DefaultArrayListCons = typeof(ArrayList).GetConstructor(EventProviderWriter.DefaultLookup, null, Array.Empty<Type>(), null );
- Debug.Assert(DefaultArrayListCons != null, "Unable to find the constructor for class ArrayList");
-
- // Temp byte array for Guid
- ubyte[] rgByteGuid = new ubyte[16];
-
- // Retrieve the constructor info for the Guid constructor.
- Type[] aParamTypes = new Type[1];
- aParamTypes[0] = typeof(Byte[]);
- ConstructorInfo ByteArrayGUIDCons = typeof(Guid).GetConstructor(EventProviderWriter.DefaultLookup, null, aParamTypes, null );
- Debug.Assert(ByteArrayGUIDCons != null, "Unable to find the constructor for GUID that accepts a string as argument");
-
- // Retrieve the IConnectionPointContainer.FindConnectionPoint() method.
- MethodInfo CPCFindCPMethod = typeof(IConnectionPointContainer).GetMethod( "FindConnectionPoint" );
- Debug.Assert(CPCFindCPMethod != null, "Unable to find the method ConnectionPointContainer.FindConnectionPoint()");
-
- // Define the Init method itself.
- MethodBuilder Meth = OutputTypeBuilder.DefineMethod(
- "Init",
- MethodAttributes.Private,
- null,
- null );
-
- ILGenerator il = Meth.GetILGenerator();
-
- // Declare the local variables.
- LocalBuilder ltCP = il.DeclareLocal( typeof(IConnectionPoint) );
- LocalBuilder ltEvGuid = il.DeclareLocal( typeof(Guid) );
- LocalBuilder ltByteArrayGuid = il.DeclareLocal( typeof(Byte[]) );
-
- // Generate the following code:
- // IConnectionPoint CP = NULL;
- il.Emit( OpCodes.Ldnull );
- il.Emit( OpCodes.Stloc, ltCP );
-
- // Get unsigned byte array for the GUID of the event interface.
- rgByteGuid = SourceInterface.GUID.ToByteArray();
-
- // Generate the following code:
- // ubyte rgByteArray[] = new ubyte [16];
- il.Emit( OpCodes.Ldc_I4, 0x10 );
- il.Emit( OpCodes.Newarr, typeof(Byte) );
- il.Emit( OpCodes.Stloc, ltByteArrayGuid );
-
- // Generate the following code:
- // rgByteArray[i] = rgByteGuid[i];
- for (int i = 0; i < 16; i++ )
- {
- il.Emit( OpCodes.Ldloc, ltByteArrayGuid );
- il.Emit( OpCodes.Ldc_I4, i );
- il.Emit( OpCodes.Ldc_I4, (int) (rgByteGuid[i]) );
- il.Emit( OpCodes.Stelem_I1);
- }
-
- // Generate the following code:
- // EventItfGuid = Guid( ubyte b[] );
- il.Emit( OpCodes.Ldloca, ltEvGuid );
- il.Emit( OpCodes.Ldloc, ltByteArrayGuid );
- il.Emit( OpCodes.Call, ByteArrayGUIDCons );
-
- // Generate the following code:
- // m_ConnectionPointContainer.FindConnectionPoint( EventItfGuid, CP );
- il.Emit( OpCodes.Ldarg, (short)0 );
- il.Emit( OpCodes.Ldfld, fbCPC );
- il.Emit( OpCodes.Ldloca, ltEvGuid );
- il.Emit( OpCodes.Ldloca, ltCP );
- il.Emit( OpCodes.Callvirt, CPCFindCPMethod );
-
- // Generate the following code:
- // m_ConnectionPoint = (IConnectionPoint)CP;
- il.Emit( OpCodes.Ldarg, (short)0 );
- il.Emit( OpCodes.Ldloc, ltCP );
- il.Emit( OpCodes.Castclass, typeof(IConnectionPoint) );
- il.Emit( OpCodes.Stfld, fbEventCP );
-
- // Generate the following code:
- // m_aEventSinkHelpers = new ArrayList;
- il.Emit( OpCodes.Ldarg, (short)0 );
- il.Emit( OpCodes.Newobj, DefaultArrayListCons );
- il.Emit( OpCodes.Stfld, fbSinkHelperArray );
-
- // Generate the return opcode.
- il.Emit( OpCodes.Ret );
-
- return Meth;
- }
-
- private void DefineConstructor( TypeBuilder OutputTypeBuilder, FieldBuilder fbCPC )
- {
- // Retrieve the constructor info for the base class's constructor.
- ConstructorInfo DefaultBaseClsCons = typeof(Object).GetConstructor(BindingFlags.Instance | BindingFlags.Public, null, Array.Empty<Type>(), null );
- Debug.Assert(DefaultBaseClsCons != null, "Unable to find the object's public default constructor");
-
- // Define the default constructor.
- MethodAttributes ctorAttributes = MethodAttributes.SpecialName | (DefaultBaseClsCons.Attributes & MethodAttributes.MemberAccessMask);
- MethodBuilder Cons = OutputTypeBuilder.DefineMethod(
- ".ctor",
- ctorAttributes,
- null,
- new Type[]{typeof(Object)} );
-
- ILGenerator il = Cons.GetILGenerator();
-
- // Generate the call to the base class constructor.
- il.Emit( OpCodes.Ldarg, (short)0 );
- il.Emit( OpCodes.Call, DefaultBaseClsCons );
-
- // Generate the following code:
- // m_ConnectionPointContainer = (IConnectionPointContainer)EventSource;
- il.Emit( OpCodes.Ldarg, (short)0 );
- il.Emit( OpCodes.Ldarg, (short)1 );
- il.Emit( OpCodes.Castclass, typeof(IConnectionPointContainer) );
- il.Emit( OpCodes.Stfld, fbCPC );
-
- // Generate the return opcode.
- il.Emit( OpCodes.Ret );
- }
-
- private MethodBuilder DefineFinalizeMethod( TypeBuilder OutputTypeBuilder, Type SinkHelperClass, FieldBuilder fbSinkHelper, FieldBuilder fbEventCP )
- {
- // Find the cookie on the event sink helper.
- FieldInfo CookieField = SinkHelperClass.GetField( "m_dwCookie" );
- Debug.Assert(CookieField != null, "Unable to find the field m_dwCookie on the sink helper");
-
- // Retrieve the ArrayList.Item property get method.
- PropertyInfo ArrayListItemProperty = typeof(ArrayList).GetProperty( "Item" );
- Debug.Assert(ArrayListItemProperty != null, "Unable to find the property ArrayList.Item");
- MethodInfo ArrayListItemGetMethod = ArrayListItemProperty.GetGetMethod();
- Debug.Assert(ArrayListItemGetMethod != null, "Unable to find the get method for property ArrayList.Item");
-
- // Retrieve the ArrayList.Count property get method.
- PropertyInfo ArrayListSizeProperty = typeof(ArrayList).GetProperty( "Count" );
- Debug.Assert(ArrayListSizeProperty != null, "Unable to find the property ArrayList.Count");
- MethodInfo ArrayListSizeGetMethod = ArrayListSizeProperty.GetGetMethod();
- Debug.Assert(ArrayListSizeGetMethod != null, "Unable to find the get method for property ArrayList.Count");
-
- // Retrieve the ConnectionPoint.Unadvise() method.
- MethodInfo CPUnadviseMethod = typeof(IConnectionPoint).GetMethod( "Unadvise" );
- Debug.Assert(CPUnadviseMethod != null, "Unable to find the method ConnectionPoint.Unadvise()");
-
- // Retrieve the Marshal.ReleaseComObject() method.
- MethodInfo ReleaseComObjectMethod = typeof(Marshal).GetMethod( "ReleaseComObject" );
- Debug.Assert(ReleaseComObjectMethod != null, "Unable to find the method Marshal.ReleaseComObject()");
-
- // Retrieve the Monitor.Enter() method.
- MethodInfo MonitorEnterMethod = typeof(Monitor).GetMethod("Enter", MonitorEnterParamTypes, null);
- Debug.Assert(MonitorEnterMethod != null, "Unable to find the method Monitor.Enter()");
-
- // Retrieve the Monitor.Exit() method.
- Type[] aParamTypes = new Type[1];
- aParamTypes[0] = typeof(Object);
- MethodInfo MonitorExitMethod = typeof(Monitor).GetMethod( "Exit", aParamTypes, null );
- Debug.Assert(MonitorExitMethod != null, "Unable to find the method Monitor.Exit()");
-
- // Define the Finalize method itself.
- MethodBuilder Meth = OutputTypeBuilder.DefineMethod( "Finalize", MethodAttributes.Public | MethodAttributes.Virtual, null, null );
-
- ILGenerator il = Meth.GetILGenerator();
-
- // Declare the local variables.
- LocalBuilder ltNumSinkHelpers = il.DeclareLocal( typeof(Int32) );
- LocalBuilder ltSinkHelperCounter = il.DeclareLocal( typeof(Int32) );
- LocalBuilder ltCurrSinkHelper = il.DeclareLocal( SinkHelperClass );
- LocalBuilder ltLockTaken = il.DeclareLocal(typeof(bool));
-
- // Generate the following code:
- // try {
- il.BeginExceptionBlock();
-
- // Generate the following code:
- // Monitor.Enter(this, ref lockTaken);
- il.Emit(OpCodes.Ldarg, (short)0);
- il.Emit(OpCodes.Ldloca_S, ltLockTaken);
- il.Emit(OpCodes.Call, MonitorEnterMethod);
-
- // Generate the labels.
- Label ForBeginLabel = il.DefineLabel();
- Label ReleaseComObjectLabel = il.DefineLabel();
- Label AfterReleaseComObjectLabel = il.DefineLabel();
-
- // Generate the following code:
- // if ( m_IFooEventsCP == null ) goto AfterReleaseComObjectLabel;
- il.Emit( OpCodes.Ldarg, (short)0 );
- il.Emit( OpCodes.Ldfld, fbEventCP );
- il.Emit( OpCodes.Brfalse, AfterReleaseComObjectLabel );
-
- // Generate the following code:
- // int NumEventHelpers = m_aIFooEventsHelpers.Count;
- // int cEventHelpers = 0;
- il.Emit( OpCodes.Ldarg, (short)0 );
- il.Emit( OpCodes.Ldfld, fbSinkHelper );
- il.Emit( OpCodes.Callvirt, ArrayListSizeGetMethod );
- il.Emit( OpCodes.Stloc, ltNumSinkHelpers );
- il.Emit( OpCodes.Ldc_I4, 0 );
- il.Emit( OpCodes.Stloc, ltSinkHelperCounter );
-
- // Generate the following code:
- // if ( 0 >= NumEventHelpers ) goto ReleaseComObjectLabel;
- il.Emit( OpCodes.Ldc_I4, 0 );
- il.Emit( OpCodes.Ldloc, ltNumSinkHelpers );
- il.Emit( OpCodes.Bge, ReleaseComObjectLabel );
-
- // Mark this as the beginning of the for loop's body.
- il.MarkLabel( ForBeginLabel );
-
- // Generate the following code:
- // CurrentHelper = (IFooEvents_SinkHelper)m_aIFooEventsHelpers.Get( cEventHelpers );
- il.Emit( OpCodes.Ldarg, (short)0 );
- il.Emit( OpCodes.Ldfld, fbSinkHelper );
- il.Emit( OpCodes.Ldloc, ltSinkHelperCounter );
- il.Emit( OpCodes.Callvirt, ArrayListItemGetMethod );
- il.Emit( OpCodes.Castclass, SinkHelperClass );
- il.Emit( OpCodes.Stloc, ltCurrSinkHelper );
-
- // Generate the following code:
- // m_IFooEventsCP.Unadvise( CurrentHelper.m_dwCookie );
- il.Emit( OpCodes.Ldarg, (short)0 );
- il.Emit( OpCodes.Ldfld, fbEventCP );
- il.Emit( OpCodes.Ldloc, ltCurrSinkHelper );
- il.Emit( OpCodes.Ldfld, CookieField );
- il.Emit( OpCodes.Callvirt, CPUnadviseMethod );
-
- // Generate the following code:
- // cEventHelpers++;
- il.Emit( OpCodes.Ldloc, ltSinkHelperCounter );
- il.Emit( OpCodes.Ldc_I4, 1 );
- il.Emit( OpCodes.Add );
- il.Emit( OpCodes.Stloc, ltSinkHelperCounter );
-
- // Generate the following code:
- // if ( cEventHelpers < NumEventHelpers ) goto ForBeginLabel;
- il.Emit( OpCodes.Ldloc, ltSinkHelperCounter );
- il.Emit( OpCodes.Ldloc, ltNumSinkHelpers );
- il.Emit( OpCodes.Blt, ForBeginLabel );
-
- // Mark this as the end of the for loop's body.
- il.MarkLabel( ReleaseComObjectLabel );
-
- // Generate the following code:
- // Marshal.ReleaseComObject(m_IFooEventsCP);
- il.Emit( OpCodes.Ldarg, (short)0 );
- il.Emit( OpCodes.Ldfld, fbEventCP );
- il.Emit( OpCodes.Call, ReleaseComObjectMethod );
- il.Emit( OpCodes.Pop );
-
- // Mark this as the end of the for loop's body.
- il.MarkLabel( AfterReleaseComObjectLabel );
-
- // Generate the following code:
- // } catch {
- il.BeginCatchBlock(typeof(System.Exception));
- il.Emit( OpCodes.Pop );
-
- // Generate the following code:
- // } finally {
- il.BeginFinallyBlock();
-
- // Generate the following code:
- // if (lockTaken)
- // Monitor.Exit(this);
- Label skipExit = il.DefineLabel();
- il.Emit(OpCodes.Ldloc, ltLockTaken);
- il.Emit(OpCodes.Brfalse_S, skipExit);
- il.Emit(OpCodes.Ldarg, (short)0);
- il.Emit(OpCodes.Call, MonitorExitMethod);
- il.MarkLabel(skipExit);
-
- // Generate the following code:
- // }
- il.EndExceptionBlock();
-
- // Generate the return opcode.
- il.Emit( OpCodes.Ret );
-
- return Meth;
- }
-
- private void DefineDisposeMethod( TypeBuilder OutputTypeBuilder, MethodBuilder FinalizeMethod )
- {
- // Retrieve the method info for GC.SuppressFinalize().
- MethodInfo SuppressFinalizeMethod = typeof(GC).GetMethod("SuppressFinalize");
- Debug.Assert(SuppressFinalizeMethod != null, "Unable to find the GC.SuppressFinalize");
-
- // Define the Finalize method itself.
- MethodBuilder Meth = OutputTypeBuilder.DefineMethod( "Dispose", MethodAttributes.Public | MethodAttributes.Virtual, null, null );
-
- ILGenerator il = Meth.GetILGenerator();
-
- // Generate the following code:
- // Finalize()
- il.Emit( OpCodes.Ldarg, (short)0 );
- il.Emit( OpCodes.Callvirt, FinalizeMethod );
-
- // Generate the following code:
- // GC.SuppressFinalize()
- il.Emit( OpCodes.Ldarg, (short)0 );
- il.Emit( OpCodes.Call, SuppressFinalizeMethod );
-
- // Generate the return opcode.
- il.Emit( OpCodes.Ret );
- }
-
- private ModuleBuilder m_OutputModule;
- private String m_strDestTypeName;
- private Type m_EventItfType;
- private Type m_SrcItfType;
- private Type m_SinkHelperType;
- }
-}
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-namespace System.Runtime.InteropServices.TCEAdapterGen {
- using System.Runtime.InteropServices;
- using System;
- using System.Reflection;
- using System.Reflection.Emit;
- using System.Collections;
- using System.Diagnostics;
- using System.Diagnostics.Contracts;
- internal class EventSinkHelperWriter
- {
- public static readonly String GeneratedTypeNamePostfix = "_SinkHelper";
-
- public EventSinkHelperWriter( ModuleBuilder OutputModule, Type InputType, Type EventItfType )
- {
- m_InputType = InputType;
- m_OutputModule = OutputModule;
- m_EventItfType = EventItfType;
- }
-
- public Type Perform()
- {
- // Create the output Type.
- Type[] aInterfaces = new Type[1];
- aInterfaces[0] = m_InputType;
- String strFullName = null;
- String strNameSpace = NameSpaceExtractor.ExtractNameSpace( m_EventItfType.FullName );
-
- if (strNameSpace != "")
- strFullName = strNameSpace + ".";
-
- strFullName += m_InputType.Name + GeneratedTypeNamePostfix;
- TypeBuilder OutputTypeBuilder = TCEAdapterGenerator.DefineUniqueType(
- strFullName,
- TypeAttributes.Sealed | TypeAttributes.Public,
- null,
- aInterfaces,
- m_OutputModule
- );
- // Hide the _SinkProvider interface
- TCEAdapterGenerator.SetHiddenAttribute(OutputTypeBuilder);
-
- // Set the class interface to none.
- TCEAdapterGenerator.SetClassInterfaceTypeToNone(OutputTypeBuilder);
-
- // Retrieve the property methods on the input interface and give them a dummy implementation.
- MethodInfo[] pMethods = TCEAdapterGenerator.GetPropertyMethods(m_InputType);
- foreach (MethodInfo method in pMethods)
- {
- DefineBlankMethod(OutputTypeBuilder, method);
- }
-
- // Retrieve the non-property methods on the input interface.
- MethodInfo[] aMethods = TCEAdapterGenerator.GetNonPropertyMethods(m_InputType);
-
- // Allocate an array to contain the delegate fields.
- FieldBuilder[] afbDelegates = new FieldBuilder[aMethods.Length];
- // Process all the methods on the input interface.
- for ( int cMethods = 0; cMethods < aMethods.Length; cMethods++ )
- {
- if ( m_InputType == aMethods[cMethods].DeclaringType )
- {
- // Retrieve the delegate type from the add_XXX method.
- MethodInfo AddMeth = m_EventItfType.GetMethod( "add_" + aMethods[cMethods].Name );
- ParameterInfo[] aParams = AddMeth.GetParameters();
- Debug.Assert(aParams.Length == 1, "All event interface methods must take a single delegate derived type and have a void return type");
- Type DelegateCls = aParams[0].ParameterType;
-
- // Define the delegate instance field.
- afbDelegates[cMethods] = OutputTypeBuilder.DefineField(
- "m_" + aMethods[cMethods].Name + "Delegate",
- DelegateCls,
- FieldAttributes.Public
- );
-
- // Define the event method itself.
- DefineEventMethod( OutputTypeBuilder, aMethods[cMethods], DelegateCls, afbDelegates[cMethods] );
- }
- }
-
- // Create the cookie field.
- FieldBuilder fbCookie = OutputTypeBuilder.DefineField(
- "m_dwCookie",
- typeof(Int32),
- FieldAttributes.Public
- );
-
- // Define the constructor.
- DefineConstructor( OutputTypeBuilder, fbCookie, afbDelegates );
-
- return OutputTypeBuilder.CreateType();
- }
-
- private void DefineBlankMethod(TypeBuilder OutputTypeBuilder, MethodInfo Method)
- {
- ParameterInfo[] PIs = Method.GetParameters();
- Type[] parameters = new Type[PIs.Length];
- for (int i=0; i < PIs.Length; i++)
- {
- parameters[i] = PIs[i].ParameterType;
- }
-
- MethodBuilder Meth = OutputTypeBuilder.DefineMethod(Method.Name,
- Method.Attributes & ~MethodAttributes.Abstract,
- Method.CallingConvention,
- Method.ReturnType,
- parameters);
-
- ILGenerator il = Meth.GetILGenerator();
-
- AddReturn(Method.ReturnType, il, Meth);
-
- il.Emit(OpCodes.Ret);
- }
-
- private void DefineEventMethod( TypeBuilder OutputTypeBuilder, MethodInfo Method, Type DelegateCls, FieldBuilder fbDelegate )
- {
- // Retrieve the method info for the invoke method on the delegate.
- MethodInfo DelegateInvokeMethod = DelegateCls.GetMethod( "Invoke" );
- Debug.Assert(DelegateInvokeMethod != null, "Unable to find method Delegate.Invoke()");
-
- // Retrieve the return type.
- Type ReturnType = Method.ReturnType;
-
- // Define the actual event method.
- ParameterInfo[] paramInfos = Method.GetParameters();
- Type[] parameterTypes;
- if (paramInfos != null)
- {
- parameterTypes = new Type[paramInfos.Length];
- for (int i = 0; i < paramInfos.Length; i++)
- {
- parameterTypes[i] = paramInfos[i].ParameterType;
- }
- }
- else
- parameterTypes = null;
-
- MethodAttributes attr = MethodAttributes.Public | MethodAttributes.Virtual;
- MethodBuilder Meth = OutputTypeBuilder.DefineMethod( Method.Name,
- attr,
- CallingConventions.Standard,
- ReturnType,
- parameterTypes);
-
- // We explicitly do not specify parameter name and attributes since this Type
- // is not meant to be exposed to the user. It is only used internally to do the
- // connection point to TCE mapping.
-
- ILGenerator il = Meth.GetILGenerator();
-
- // Create the exit branch.
- Label ExitLabel = il.DefineLabel();
-
- // Generate the code that verifies that the delegate is not null.
- il.Emit( OpCodes.Ldarg, (short)0 );
- il.Emit( OpCodes.Ldfld, fbDelegate );
- il.Emit( OpCodes.Brfalse, ExitLabel );
-
- // The delegate is not NULL so we need to invoke it.
- il.Emit( OpCodes.Ldarg, (short)0 );
- il.Emit( OpCodes.Ldfld, fbDelegate );
-
- // Generate the code to load the arguments before we call invoke.
- ParameterInfo[] aParams = Method.GetParameters();
- for ( int cParams = 0; cParams < aParams.Length; cParams++ )
- {
- il.Emit( OpCodes.Ldarg, (short)(cParams + 1) );
- }
-
- // Generate a tail call to invoke. This will cause the callvirt to return
- // directly to the caller of the current method instead of actually coming
- // back to the current method and returning. This will cause the value returned
- // from the call to the COM server to be returned to the caller of this method.
-
- il.Emit( OpCodes.Callvirt, DelegateInvokeMethod );
- il.Emit( OpCodes.Ret );
-
- // This is the label that will be jumped to if no delegate is present.
- il.MarkLabel( ExitLabel );
-
- AddReturn(ReturnType, il, Meth);
-
- il.Emit( OpCodes.Ret );
-
- }
-
- private void AddReturn(Type ReturnType, ILGenerator il, MethodBuilder Meth)
- {
- // Place a dummy return value on the stack before we return.
- if ( ReturnType == typeof(void) )
- {
- // There is nothing to place on the stack.
- }
- else if ( ReturnType.IsPrimitive )
- {
- switch (System.Type.GetTypeCode(ReturnType))
- {
- case TypeCode.Boolean:
- case TypeCode.Char:
- case TypeCode.Byte:
- case TypeCode.SByte:
- case TypeCode.Int16:
- case TypeCode.UInt16:
- case TypeCode.Int32:
- case TypeCode.UInt32:
- il.Emit( OpCodes.Ldc_I4_0 );
- break;
-
- case TypeCode.Int64:
- case TypeCode.UInt64:
- il.Emit( OpCodes.Ldc_I4_0 );
- il.Emit( OpCodes.Conv_I8 );
- break;
-
- case TypeCode.Single:
- il.Emit( OpCodes.Ldc_R4, 0 );
- break;
-
- case TypeCode.Double:
- il.Emit( OpCodes.Ldc_R4, 0 );
- il.Emit( OpCodes.Conv_R8 );
- break;
-
- default:
- // "TypeCode" does not include IntPtr, so special case it.
- if ( ReturnType == typeof(IntPtr) )
- il.Emit( OpCodes.Ldc_I4_0 );
- else
- Debug.Assert(false, "Unexpected type for Primitive type.");
- break;
- }
- }
- else if ( ReturnType.IsValueType )
- {
- // Allocate stack space for the return value type. Zero-init.
- Meth.InitLocals = true;
- LocalBuilder ltRetVal = il.DeclareLocal( ReturnType );
-
- // Load the value class on the stack.
- il.Emit( OpCodes.Ldloc_S, ltRetVal );
-
- }
- else
- {
- // The return type is a normal type.
- il.Emit( OpCodes.Ldnull );
- }
- }
-
- private void DefineConstructor( TypeBuilder OutputTypeBuilder, FieldBuilder fbCookie, FieldBuilder[] afbDelegates )
- {
- // Retrieve the constructor info for the base classe's constructor.
- ConstructorInfo DefaultBaseClsCons = typeof(Object).GetConstructor(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public, null, Array.Empty<Type>(), null );
- Debug.Assert(DefaultBaseClsCons != null, "Unable to find the constructor for class " + m_InputType.Name);
-
- // Define the default constructor.
- MethodBuilder Cons = OutputTypeBuilder.DefineMethod( ".ctor",
- MethodAttributes.Assembly | MethodAttributes.SpecialName,
- CallingConventions.Standard,
- null,
- null);
-
- ILGenerator il = Cons.GetILGenerator();
-
- // Generate the code to call the constructor of the base class.
- il.Emit( OpCodes.Ldarg, (short)0 );
- il.Emit( OpCodes.Call, DefaultBaseClsCons );
-
- // Generate the code to set the cookie field to 0.
- il.Emit( OpCodes.Ldarg, (short)0 );
- il.Emit( OpCodes.Ldc_I4, 0 );
- il.Emit( OpCodes.Stfld, fbCookie );
-
- // Generate the code to set all the delegates to NULL.
- for ( int cDelegates = 0; cDelegates < afbDelegates.Length; cDelegates++ )
- {
- if (afbDelegates[cDelegates] != null)
- {
- il.Emit( OpCodes.Ldarg,(short)0 );
- il.Emit( OpCodes.Ldnull );
- il.Emit( OpCodes.Stfld, afbDelegates[cDelegates] );
- }
- }
-
- // Emit the return opcode.
- il.Emit( OpCodes.Ret );
-
- }
-
- private Type m_InputType;
- private Type m_EventItfType;
- private ModuleBuilder m_OutputModule;
- }
-}
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-namespace System.Runtime.InteropServices.TCEAdapterGen {
-
- using System;
- internal static class NameSpaceExtractor
- {
- private static char NameSpaceSeperator = '.';
-
- public static String ExtractNameSpace(String FullyQualifiedTypeName)
- {
- int TypeNameStartPos = FullyQualifiedTypeName.LastIndexOf(NameSpaceSeperator);
- if (TypeNameStartPos == -1)
- return "";
- else
- return FullyQualifiedTypeName.Substring(0, TypeNameStartPos);
- }
- }
-}
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-namespace System.Runtime.InteropServices.TCEAdapterGen {
- using System.Runtime.InteropServices;
- using System;
- using System.Reflection;
- using System.Reflection.Emit;
- using System.Collections;
- using System.Threading;
-
- internal class TCEAdapterGenerator
- {
- public void Process(ModuleBuilder ModBldr, ArrayList EventItfList)
- {
- // Store the input/output module.
- m_Module = ModBldr;
-
- // Generate the TCE adapters for all the event sources.
- int NumEvItfs = EventItfList.Count;
- for ( int cEventItfs = 0; cEventItfs < NumEvItfs; cEventItfs++ )
- {
- // Retrieve the event interface info.
- EventItfInfo CurrEventItf = (EventItfInfo)EventItfList[cEventItfs];
-
- // Retrieve the information from the event interface info.
- Type EventItfType = CurrEventItf.GetEventItfType();
- Type SrcItfType = CurrEventItf.GetSrcItfType();
- String EventProviderName = CurrEventItf.GetEventProviderName();
-
- // Generate the sink interface helper.
- Type SinkHelperType = new EventSinkHelperWriter( m_Module, SrcItfType, EventItfType ).Perform();
-
- // Generate the event provider.
- new EventProviderWriter( m_Module, EventProviderName, EventItfType, SrcItfType, SinkHelperType ).Perform();
- }
- }
-
- internal static void SetClassInterfaceTypeToNone(TypeBuilder tb)
- {
- // Create the ClassInterface(ClassInterfaceType.None) CA builder if we haven't created it yet.
- if (s_NoClassItfCABuilder == null)
- {
- Type []aConsParams = new Type[1];
- aConsParams[0] = typeof(ClassInterfaceType);
- ConstructorInfo Cons = typeof(ClassInterfaceAttribute).GetConstructor(aConsParams);
-
- Object[] aArgs = new Object[1];
- aArgs[0] = ClassInterfaceType.None;
- s_NoClassItfCABuilder = new CustomAttributeBuilder(Cons, aArgs);
- }
-
- // Set the class interface type to none.
- tb.SetCustomAttribute(s_NoClassItfCABuilder);
- }
-
- internal static TypeBuilder DefineUniqueType(String strInitFullName, TypeAttributes attrs, Type BaseType, Type[] aInterfaceTypes, ModuleBuilder mb)
- {
- String strFullName = strInitFullName;
- int PostFix = 2;
-
- // Find the first unique name for the type.
- for (; mb.GetType(strFullName) != null; strFullName = strInitFullName + "_" + PostFix, PostFix++);
-
- // Define a type with the determined unique name.
- return mb.DefineType(strFullName, attrs, BaseType, aInterfaceTypes);
- }
-
- internal static void SetHiddenAttribute(TypeBuilder tb)
- {
- if (s_HiddenCABuilder == null)
- {
- // Hide the type from Object Browsers
- Type []aConsParams = new Type[1];
- aConsParams[0] = typeof(TypeLibTypeFlags);
- ConstructorInfo Cons = typeof(TypeLibTypeAttribute).GetConstructor(aConsParams);
-
- Object []aArgs = new Object[1];
- aArgs[0] = TypeLibTypeFlags.FHidden;
- s_HiddenCABuilder = new CustomAttributeBuilder(Cons, aArgs);
- }
-
- tb.SetCustomAttribute(s_HiddenCABuilder);
- }
-
- internal static MethodInfo[] GetNonPropertyMethods(Type type)
- {
- MethodInfo[] aMethods = type.GetMethods();
- ArrayList methods = new ArrayList(aMethods);
-
- PropertyInfo[] props = type.GetProperties();
-
- foreach(PropertyInfo prop in props)
- {
- MethodInfo[] accessors = prop.GetAccessors();
- foreach (MethodInfo accessor in accessors)
- {
- for (int i=0; i < methods.Count; i++)
- {
- if ((MethodInfo)methods[i] == accessor)
- methods.RemoveAt(i);
- }
- }
- }
-
- MethodInfo[] retMethods = new MethodInfo[methods.Count];
- methods.CopyTo(retMethods);
-
- return retMethods;
- }
-
- internal static MethodInfo[] GetPropertyMethods(Type type)
- {
- MethodInfo[] aMethods = type.GetMethods();
- ArrayList methods = new ArrayList();
-
- PropertyInfo[] props = type.GetProperties();
-
- foreach(PropertyInfo prop in props)
- {
- MethodInfo[] accessors = prop.GetAccessors();
- foreach (MethodInfo accessor in accessors)
- {
- methods.Add(accessor);
- }
- }
-
- MethodInfo[] retMethods = new MethodInfo[methods.Count];
- methods.CopyTo(retMethods);
-
- return retMethods;
- }
-
-
- private ModuleBuilder m_Module = null;
- private Hashtable m_SrcItfToSrcItfInfoMap = new Hashtable();
- private static volatile CustomAttributeBuilder s_NoClassItfCABuilder = null;
- private static volatile CustomAttributeBuilder s_HiddenCABuilder = null;
- }
-}
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-/*=============================================================================
-**
-**
-**
-** Purpose: UCOMIBindCtx interface definition.
-**
-**
-=============================================================================*/
-
-namespace System.Runtime.InteropServices {
-
- using System;
-
- [Obsolete("Use System.Runtime.InteropServices.ComTypes.BIND_OPTS instead. http://go.microsoft.com/fwlink/?linkid=14202", false)]
- [StructLayout(LayoutKind.Sequential)]
-
- public struct BIND_OPTS
- {
- public int cbStruct;
- public int grfFlags;
- public int grfMode;
- public int dwTickCountDeadline;
- }
-
- [Obsolete("Use System.Runtime.InteropServices.ComTypes.IBindCtx instead. http://go.microsoft.com/fwlink/?linkid=14202", false)]
- [Guid("0000000e-0000-0000-C000-000000000046")]
- [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
- [ComImport]
- public interface UCOMIBindCtx
- {
- void RegisterObjectBound([MarshalAs(UnmanagedType.Interface)] Object punk);
- void RevokeObjectBound([MarshalAs(UnmanagedType.Interface)] Object punk);
- void ReleaseBoundObjects();
- void SetBindOptions([In()] ref BIND_OPTS pbindopts);
- void GetBindOptions(ref BIND_OPTS pbindopts);
- void GetRunningObjectTable(out UCOMIRunningObjectTable pprot);
- void RegisterObjectParam([MarshalAs(UnmanagedType.LPWStr)] String pszKey, [MarshalAs(UnmanagedType.Interface)] Object punk);
- void GetObjectParam([MarshalAs(UnmanagedType.LPWStr)] String pszKey, [MarshalAs(UnmanagedType.Interface)] out Object ppunk);
- void EnumObjectParam(out UCOMIEnumString ppenum);
- void RevokeObjectParam([MarshalAs(UnmanagedType.LPWStr)] String pszKey);
- }
-}
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-/*=============================================================================
-**
-**
-**
-** Purpose: UCOMIConnectionPoint interface definition.
-**
-**
-=============================================================================*/
-
-namespace System.Runtime.InteropServices
-{
- using System;
-
- [Obsolete("Use System.Runtime.InteropServices.ComTypes.IConnectionPoint instead. http://go.microsoft.com/fwlink/?linkid=14202", false)]
- [Guid("B196B286-BAB4-101A-B69C-00AA00341D07")]
- [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
- [ComImport]
- public interface UCOMIConnectionPoint
- {
- void GetConnectionInterface(out Guid pIID);
- void GetConnectionPointContainer(out UCOMIConnectionPointContainer ppCPC);
- void Advise([MarshalAs(UnmanagedType.Interface)] Object pUnkSink, out int pdwCookie);
- void Unadvise(int dwCookie);
- void EnumConnections(out UCOMIEnumConnections ppEnum);
- }
-}
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-/*=============================================================================
-**
-**
-**
-** Purpose: UCOMIConnectionPointContainer interface definition.
-**
-**
-=============================================================================*/
-
-namespace System.Runtime.InteropServices
-{
- using System;
-
- [Obsolete("Use System.Runtime.InteropServices.ComTypes.IConnectionPointContainer instead. http://go.microsoft.com/fwlink/?linkid=14202", false)]
- [Guid("B196B284-BAB4-101A-B69C-00AA00341D07")]
- [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
- [ComImport]
- public interface UCOMIConnectionPointContainer
- {
- void EnumConnectionPoints(out UCOMIEnumConnectionPoints ppEnum);
- void FindConnectionPoint(ref Guid riid, out UCOMIConnectionPoint ppCP);
- }
-}
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-/*=============================================================================
-**
-**
-**
-** Purpose: UCOMIEnumConnectionPoints interface definition.
-**
-**
-=============================================================================*/
-
-namespace System.Runtime.InteropServices
-{
- using System;
-
- [Obsolete("Use System.Runtime.InteropServices.ComTypes.IEnumConnectionPoints instead. http://go.microsoft.com/fwlink/?linkid=14202", false)]
- [Guid("B196B285-BAB4-101A-B69C-00AA00341D07")]
- [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
- [ComImport]
- public interface UCOMIEnumConnectionPoints
- {
- [PreserveSig]
- int Next(int celt, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 0), Out] UCOMIConnectionPoint[] rgelt, out int pceltFetched);
- [PreserveSig]
- int Skip(int celt);
- [PreserveSig]
- int Reset();
- void Clone(out UCOMIEnumConnectionPoints ppenum);
- }
-}
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-/*=============================================================================
-**
-**
-**
-** Purpose: UCOMIEnumConnections interface definition.
-**
-**
-=============================================================================*/
-
-namespace System.Runtime.InteropServices
-{
- using System;
-
- [Obsolete("Use System.Runtime.InteropServices.ComTypes.CONNECTDATA instead. http://go.microsoft.com/fwlink/?linkid=14202", false)]
- [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
-
- public struct CONNECTDATA
- {
- [MarshalAs(UnmanagedType.Interface)]
- public Object pUnk;
- public int dwCookie;
- }
-
- [Obsolete("Use System.Runtime.InteropServices.ComTypes.IEnumConnections instead. http://go.microsoft.com/fwlink/?linkid=14202", false)]
- [Guid("B196B287-BAB4-101A-B69C-00AA00341D07")]
- [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
- [ComImport]
- public interface UCOMIEnumConnections
- {
- [PreserveSig]
- int Next(int celt, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 0), Out] CONNECTDATA[] rgelt, out int pceltFetched);
- [PreserveSig]
- int Skip(int celt);
- [PreserveSig]
- void Reset();
- void Clone(out UCOMIEnumConnections ppenum);
- }
-}
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-/*=============================================================================
-**
-**
-**
-** Purpose: UCOMIEnumMoniker interface definition.
-**
-**
-=============================================================================*/
-
-namespace System.Runtime.InteropServices
-{
- using System;
- using DWORD = System.UInt32;
-
- [Obsolete("Use System.Runtime.InteropServices.ComTypes.IEnumMoniker instead. http://go.microsoft.com/fwlink/?linkid=14202", false)]
- [Guid("00000102-0000-0000-C000-000000000046")]
- [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
- [ComImport]
- public interface UCOMIEnumMoniker
- {
- [PreserveSig]
- int Next(int celt, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 0), Out] UCOMIMoniker[] rgelt, out int pceltFetched);
- [PreserveSig]
- int Skip(int celt);
- [PreserveSig]
- int Reset();
- void Clone(out UCOMIEnumMoniker ppenum);
- }
-}
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-/*=============================================================================
-**
-**
-**
-** Purpose: UCOMIEnumString interface definition.
-**
-**
-=============================================================================*/
-
-namespace System.Runtime.InteropServices
-{
- using System;
-
- [Obsolete("Use System.Runtime.InteropServices.ComTypes.IEnumString instead. http://go.microsoft.com/fwlink/?linkid=14202", false)]
- [Guid("00000101-0000-0000-C000-000000000046")]
- [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
- [ComImport]
- public interface UCOMIEnumString
- {
- [PreserveSig]
- int Next(int celt, [MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.LPWStr, SizeParamIndex = 0), Out] String[] rgelt, out int pceltFetched);
- [PreserveSig]
- int Skip(int celt);
- [PreserveSig]
- int Reset();
- void Clone(out UCOMIEnumString ppenum);
- }
-}
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-/*=============================================================================
-**
-**
-**
-** Purpose: UCOMIEnumVARIANT interface definition.
-**
-**
-=============================================================================*/
-
-namespace System.Runtime.InteropServices
-{
- using System;
-
- [Obsolete("Use System.Runtime.InteropServices.ComTypes.IEnumVARIANT instead. http://go.microsoft.com/fwlink/?linkid=14202", false)]
- [Guid("00020404-0000-0000-C000-000000000046")]
- [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
- [ComImport]
- public interface UCOMIEnumVARIANT
- {
- [PreserveSig]
- int Next(int celt, int rgvar, int pceltFetched);
-
- [PreserveSig]
- int Skip(int celt);
-
- [PreserveSig]
- int Reset();
-
- void Clone(int ppenum);
- }
-}
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-/*==========================================================================
-**
-** Interface: UCOMIEnumerable
-**
-**
-** Purpose:
-** This interface is redefined here since the original IEnumerable interface
-** has all its methods marked as ecall's since it is a managed standard
-** interface. This interface is used from within the runtime to make a call
-** on the COM server directly when it implements the IEnumerable interface.
-**
-**
-==========================================================================*/
-namespace System.Runtime.InteropServices
-{
- using System;
- using System.Collections;
-
- [Obsolete("Use System.Runtime.InteropServices.ComTypes.IEnumerable instead. http://go.microsoft.com/fwlink/?linkid=14202", false)]
- [Guid("496B0ABE-CDEE-11d3-88E8-00902754C43A")]
- internal interface UCOMIEnumerable
- {
- [DispId(-4)]
- IEnumerator GetEnumerator();
- }
-}
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-/*==========================================================================
-**
-** Interface: UCOMIEnumerator
-**
-**
-** Purpose:
-** This interface is redefined here since the original IEnumerator interface
-** has all its methods marked as ecall's since it is a managed standard
-** interface. This interface is used from within the runtime to make a call
-** on the COM server directly when it implements the IEnumerator interface.
-**
-**
-==========================================================================*/
-namespace System.Runtime.InteropServices
-{
- using System;
-
- [Obsolete("Use System.Runtime.InteropServices.ComTypes.IEnumerator instead. http://go.microsoft.com/fwlink/?linkid=14202", false)]
- [Guid("496B0ABF-CDEE-11d3-88E8-00902754C43A")]
- internal interface UCOMIEnumerator
- {
- bool MoveNext();
- Object Current {
- get;
- }
- void Reset();
- }
-}
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-/*==========================================================================
-**
-** Interface: UCOMIExpando
-**
-**
-** Purpose:
-** This interface is redefined here since the original IExpando interface
-** has all its methods marked as ecall's since it is a managed standard
-** interface. This interface is used from within the runtime to make a call
-** on the COM server directly when it implements the IExpando interface.
-**
-**
-==========================================================================*/
-namespace System.Runtime.InteropServices
-{
-
- using System;
- using System.Reflection;
-
- [Obsolete("Use System.Runtime.InteropServices.ComTypes.IExpando instead. http://go.microsoft.com/fwlink/?linkid=14202", false)]
- [Guid("AFBF15E6-C37C-11d2-B88E-00A0C9B471B8")]
- internal interface UCOMIExpando : UCOMIReflect
- {
- FieldInfo AddField(String name);
- PropertyInfo AddProperty(String name);
- MethodInfo AddMethod(String name, Delegate method);
- void RemoveMember(MemberInfo m);
- }
-}
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-/*=============================================================================
-**
-**
-**
-** Purpose: UCOMIMoniker interface definition.
-**
-**
-=============================================================================*/
-
-namespace System.Runtime.InteropServices
-{
- using System;
-
- [Obsolete("Use System.Runtime.InteropServices.ComTypes.FILETIME instead. http://go.microsoft.com/fwlink/?linkid=14202", false)]
- [StructLayout(LayoutKind.Sequential)]
-
- public struct FILETIME
- {
- public int dwLowDateTime;
- public int dwHighDateTime;
- }
-
- [Obsolete("Use System.Runtime.InteropServices.ComTypes.IMoniker instead. http://go.microsoft.com/fwlink/?linkid=14202", false)]
- [Guid("0000000f-0000-0000-C000-000000000046")]
- [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
- [ComImport]
- public interface UCOMIMoniker
- {
- // IPersist portion
- void GetClassID(out Guid pClassID);
-
- // IPersistStream portion
- [PreserveSig]
- int IsDirty();
- void Load(UCOMIStream pStm);
- void Save(UCOMIStream pStm, [MarshalAs(UnmanagedType.Bool)] bool fClearDirty);
- void GetSizeMax(out Int64 pcbSize);
-
- // IMoniker portion
- void BindToObject(UCOMIBindCtx pbc, UCOMIMoniker pmkToLeft, [In()] ref Guid riidResult, [MarshalAs(UnmanagedType.Interface)] out Object ppvResult);
- void BindToStorage(UCOMIBindCtx pbc, UCOMIMoniker pmkToLeft, [In()] ref Guid riid, [MarshalAs(UnmanagedType.Interface)] out Object ppvObj);
- void Reduce(UCOMIBindCtx pbc, int dwReduceHowFar, ref UCOMIMoniker ppmkToLeft, out UCOMIMoniker ppmkReduced);
- void ComposeWith(UCOMIMoniker pmkRight, [MarshalAs(UnmanagedType.Bool)] bool fOnlyIfNotGeneric, out UCOMIMoniker ppmkComposite);
- void Enum([MarshalAs(UnmanagedType.Bool)] bool fForward, out UCOMIEnumMoniker ppenumMoniker);
- void IsEqual(UCOMIMoniker pmkOtherMoniker);
- void Hash(out int pdwHash);
- void IsRunning(UCOMIBindCtx pbc, UCOMIMoniker pmkToLeft, UCOMIMoniker pmkNewlyRunning);
- void GetTimeOfLastChange(UCOMIBindCtx pbc, UCOMIMoniker pmkToLeft, out FILETIME pFileTime);
- void Inverse(out UCOMIMoniker ppmk);
- void CommonPrefixWith(UCOMIMoniker pmkOther, out UCOMIMoniker ppmkPrefix);
- void RelativePathTo(UCOMIMoniker pmkOther, out UCOMIMoniker ppmkRelPath);
- void GetDisplayName(UCOMIBindCtx pbc, UCOMIMoniker pmkToLeft, [MarshalAs(UnmanagedType.LPWStr)] out String ppszDisplayName);
- void ParseDisplayName(UCOMIBindCtx pbc, UCOMIMoniker pmkToLeft, [MarshalAs(UnmanagedType.LPWStr)] String pszDisplayName, out int pchEaten, out UCOMIMoniker ppmkOut);
- void IsSystemMoniker(out int pdwMksys);
- }
-}
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-/*=============================================================================
-**
-**
-**
-** Purpose: UCOMIPersistFile interface definition.
-**
-**
-=============================================================================*/
-
-namespace System.Runtime.InteropServices {
-
- using System;
- using DWORD = System.UInt32;
-
- [Obsolete("Use System.Runtime.InteropServices.ComTypes.IPersistFile instead. http://go.microsoft.com/fwlink/?linkid=14202", false)]
- [Guid("0000010b-0000-0000-C000-000000000046")]
- [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
- [ComImport]
- public interface UCOMIPersistFile
- {
- // IPersist portion
- void GetClassID(out Guid pClassID);
-
- // IPersistFile portion
- [PreserveSig]
- int IsDirty();
- void Load([MarshalAs(UnmanagedType.LPWStr)] String pszFileName, int dwMode);
- void Save([MarshalAs(UnmanagedType.LPWStr)] String pszFileName, [MarshalAs(UnmanagedType.Bool)] bool fRemember);
- void SaveCompleted([MarshalAs(UnmanagedType.LPWStr)] String pszFileName);
- void GetCurFile([MarshalAs(UnmanagedType.LPWStr)] out String ppszFileName);
- }
-}
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-/*==========================================================================
-**
-** Interface: UCOMIReflect
-**
-**
-** Purpose:
-** This interface is redefined here since the original IReflect interface
-** has all its methods marked as ecall's since it is a managed standard
-** interface. This interface is used from within the runtime to make a call
-** on the COM server directly when it implements the IReflect interface.
-**
-**
-==========================================================================*/
-namespace System.Runtime.InteropServices
-{
- using System;
- using System.Reflection;
- using CultureInfo = System.Globalization.CultureInfo;
-
- [Obsolete("Use System.Runtime.InteropServices.ComTypes.IReflect instead. http://go.microsoft.com/fwlink/?linkid=14202", false)]
- [Guid("AFBF15E5-C37C-11d2-B88E-00A0C9B471B8")]
- internal interface UCOMIReflect
- {
- MethodInfo GetMethod(String name,BindingFlags bindingAttr,Binder binder,
- Type[] types,ParameterModifier[] modifiers);
-
- MethodInfo GetMethod(String name,BindingFlags bindingAttr);
-
- MethodInfo[] GetMethods(
- BindingFlags bindingAttr);
-
- FieldInfo GetField(
- String name,
- BindingFlags bindingAttr);
-
- FieldInfo[] GetFields(
- BindingFlags bindingAttr);
-
- PropertyInfo GetProperty(
- String name,
- BindingFlags bindingAttr);
-
- PropertyInfo GetProperty(
- String name,
- BindingFlags bindingAttr,
- Binder binder,
- Type returnType,
- Type[] types,
- ParameterModifier[] modifiers);
-
- PropertyInfo[] GetProperties(
- BindingFlags bindingAttr);
-
- MemberInfo[] GetMember(
- String name,
- BindingFlags bindingAttr);
-
- MemberInfo[] GetMembers(
- BindingFlags bindingAttr);
-
- Object InvokeMember(
- String name,
- BindingFlags invokeAttr,
- Binder binder,
- Object target,
- Object[] args,
- ParameterModifier[] modifiers,
- CultureInfo culture,
- String[] namedParameters);
-
- Type UnderlyingSystemType {
- get;
- }
- }
-}
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-/*=============================================================================
-**
-**
-**
-** Purpose: UCOMIRunningObjectTable interface definition.
-**
-**
-=============================================================================*/
-
-namespace System.Runtime.InteropServices
-{
- using System;
-
- [Obsolete("Use System.Runtime.InteropServices.ComTypes.IRunningObjectTable instead. http://go.microsoft.com/fwlink/?linkid=14202", false)]
- [Guid("00000010-0000-0000-C000-000000000046")]
- [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
- [ComImport]
- public interface UCOMIRunningObjectTable
- {
- void Register(int grfFlags, [MarshalAs(UnmanagedType.Interface)] Object punkObject, UCOMIMoniker pmkObjectName, out int pdwRegister);
- void Revoke(int dwRegister);
- void IsRunning(UCOMIMoniker pmkObjectName);
- void GetObject(UCOMIMoniker pmkObjectName, [MarshalAs(UnmanagedType.Interface)] out Object ppunkObject);
- void NoteChangeTime(int dwRegister, ref FILETIME pfiletime);
- void GetTimeOfLastChange(UCOMIMoniker pmkObjectName, out FILETIME pfiletime);
- void EnumRunning(out UCOMIEnumMoniker ppenumMoniker);
- }
-}
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-/*=============================================================================
-**
-**
-**
-** Purpose: UCOMIStream interface definition.
-**
-**
-=============================================================================*/
-
-namespace System.Runtime.InteropServices
-{
- using System;
-
- [Obsolete("Use System.Runtime.InteropServices.ComTypes.STATSTG instead. http://go.microsoft.com/fwlink/?linkid=14202", false)]
- [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
-
- public struct STATSTG
- {
- public String pwcsName;
- public int type;
- public Int64 cbSize;
- public FILETIME mtime;
- public FILETIME ctime;
- public FILETIME atime;
- public int grfMode;
- public int grfLocksSupported;
- public Guid clsid;
- public int grfStateBits;
- public int reserved;
- }
-
- [Obsolete("Use System.Runtime.InteropServices.ComTypes.IStream instead. http://go.microsoft.com/fwlink/?linkid=14202", false)]
- [Guid("0000000c-0000-0000-C000-000000000046")]
- [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
- [ComImport]
- public interface UCOMIStream
- {
- // ISequentialStream portion
- void Read([MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1), Out] Byte[] pv, int cb,IntPtr pcbRead);
- void Write([MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] Byte[] pv, int cb, IntPtr pcbWritten);
-
- // IStream portion
- void Seek(Int64 dlibMove, int dwOrigin, IntPtr plibNewPosition);
- void SetSize(Int64 libNewSize);
- void CopyTo(UCOMIStream pstm, Int64 cb, IntPtr pcbRead, IntPtr pcbWritten);
- void Commit(int grfCommitFlags);
- void Revert();
- void LockRegion(Int64 libOffset, Int64 cb, int dwLockType);
- void UnlockRegion(Int64 libOffset, Int64 cb, int dwLockType);
- void Stat(out STATSTG pstatstg, int grfStatFlag);
- void Clone(out UCOMIStream ppstm);
- }
-}
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-/*=============================================================================
-**
-**
-**
-** Purpose: UCOMITypeComp interface definition.
-**
-**
-=============================================================================*/
-
-namespace System.Runtime.InteropServices
-{
- using System;
-
- [Obsolete("Use System.Runtime.InteropServices.ComTypes.DESCKIND instead. http://go.microsoft.com/fwlink/?linkid=14202", false)]
- [Serializable]
- public enum DESCKIND
- {
- DESCKIND_NONE = 0,
- DESCKIND_FUNCDESC = DESCKIND_NONE + 1,
- DESCKIND_VARDESC = DESCKIND_FUNCDESC + 1,
- DESCKIND_TYPECOMP = DESCKIND_VARDESC + 1,
- DESCKIND_IMPLICITAPPOBJ = DESCKIND_TYPECOMP + 1,
- DESCKIND_MAX = DESCKIND_IMPLICITAPPOBJ + 1
- }
-
- [Obsolete("Use System.Runtime.InteropServices.ComTypes.BINDPTR instead. http://go.microsoft.com/fwlink/?linkid=14202", false)]
- [StructLayout(LayoutKind.Explicit, CharSet=CharSet.Unicode)]
-
- public struct BINDPTR
- {
- [FieldOffset(0)]
- public IntPtr lpfuncdesc;
- [FieldOffset(0)]
- public IntPtr lpvardesc;
- [FieldOffset(0)]
- public IntPtr lptcomp;
- }
-
- [Obsolete("Use System.Runtime.InteropServices.ComTypes.ITypeComp instead. http://go.microsoft.com/fwlink/?linkid=14202", false)]
- [Guid("00020403-0000-0000-C000-000000000046")]
- [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
- [ComImport]
- public interface UCOMITypeComp
- {
- void Bind([MarshalAs(UnmanagedType.LPWStr)] String szName, int lHashVal, Int16 wFlags, out UCOMITypeInfo ppTInfo, out DESCKIND pDescKind, out BINDPTR pBindPtr);
- void BindType([MarshalAs(UnmanagedType.LPWStr)] String szName, int lHashVal, out UCOMITypeInfo ppTInfo, out UCOMITypeComp ppTComp);
- }
-}
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-/*=============================================================================
-**
-**
-**
-** Purpose: UCOMITypeInfo interface definition.
-**
-**
-=============================================================================*/
-
-namespace System.Runtime.InteropServices
-{
- using System;
-
- [Obsolete("Use System.Runtime.InteropServices.ComTypes.TYPEKIND instead. http://go.microsoft.com/fwlink/?linkid=14202", false)]
- [Serializable]
- public enum TYPEKIND
- {
- TKIND_ENUM = 0,
- TKIND_RECORD = TKIND_ENUM + 1,
- TKIND_MODULE = TKIND_RECORD + 1,
- TKIND_INTERFACE = TKIND_MODULE + 1,
- TKIND_DISPATCH = TKIND_INTERFACE + 1,
- TKIND_COCLASS = TKIND_DISPATCH + 1,
- TKIND_ALIAS = TKIND_COCLASS + 1,
- TKIND_UNION = TKIND_ALIAS + 1,
- TKIND_MAX = TKIND_UNION + 1
- }
-
- [Obsolete("Use System.Runtime.InteropServices.ComTypes.TYPEFLAGS instead. http://go.microsoft.com/fwlink/?linkid=14202", false)]
-[Serializable]
-[Flags()]
- public enum TYPEFLAGS : short
- {
- TYPEFLAG_FAPPOBJECT = 0x1,
- TYPEFLAG_FCANCREATE = 0x2,
- TYPEFLAG_FLICENSED = 0x4,
- TYPEFLAG_FPREDECLID = 0x8,
- TYPEFLAG_FHIDDEN = 0x10,
- TYPEFLAG_FCONTROL = 0x20,
- TYPEFLAG_FDUAL = 0x40,
- TYPEFLAG_FNONEXTENSIBLE = 0x80,
- TYPEFLAG_FOLEAUTOMATION = 0x100,
- TYPEFLAG_FRESTRICTED = 0x200,
- TYPEFLAG_FAGGREGATABLE = 0x400,
- TYPEFLAG_FREPLACEABLE = 0x800,
- TYPEFLAG_FDISPATCHABLE = 0x1000,
- TYPEFLAG_FREVERSEBIND = 0x2000,
- TYPEFLAG_FPROXY = 0x4000
- }
-
- [Obsolete("Use System.Runtime.InteropServices.ComTypes.IMPLTYPEFLAGS instead. http://go.microsoft.com/fwlink/?linkid=14202", false)]
-[Serializable]
-[Flags()]
- public enum IMPLTYPEFLAGS
- {
- IMPLTYPEFLAG_FDEFAULT = 0x1,
- IMPLTYPEFLAG_FSOURCE = 0x2,
- IMPLTYPEFLAG_FRESTRICTED = 0x4,
- IMPLTYPEFLAG_FDEFAULTVTABLE = 0x8,
- }
-
- [Obsolete("Use System.Runtime.InteropServices.ComTypes.TYPEATTR instead. http://go.microsoft.com/fwlink/?linkid=14202", false)]
- [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
- public struct TYPEATTR
- {
- // Constant used with the memid fields.
- public const int MEMBER_ID_NIL = unchecked((int)0xFFFFFFFF);
-
- // Actual fields of the TypeAttr struct.
- public Guid guid;
- public Int32 lcid;
- public Int32 dwReserved;
- public Int32 memidConstructor;
- public Int32 memidDestructor;
- public IntPtr lpstrSchema;
- public Int32 cbSizeInstance;
- public TYPEKIND typekind;
- public Int16 cFuncs;
- public Int16 cVars;
- public Int16 cImplTypes;
- public Int16 cbSizeVft;
- public Int16 cbAlignment;
- public TYPEFLAGS wTypeFlags;
- public Int16 wMajorVerNum;
- public Int16 wMinorVerNum;
- public TYPEDESC tdescAlias;
- public IDLDESC idldescType;
- }
-
- [Obsolete("Use System.Runtime.InteropServices.ComTypes.FUNCDESC instead. http://go.microsoft.com/fwlink/?linkid=14202", false)]
- [StructLayout(LayoutKind.Sequential)]
- public struct FUNCDESC
- {
- public int memid; //MEMBERID memid;
- public IntPtr lprgscode; // /* [size_is(cScodes)] */ SCODE RPC_FAR *lprgscode;
- public IntPtr lprgelemdescParam; // /* [size_is(cParams)] */ ELEMDESC __RPC_FAR *lprgelemdescParam;
- public FUNCKIND funckind; //FUNCKIND funckind;
- public INVOKEKIND invkind; //INVOKEKIND invkind;
- public CALLCONV callconv; //CALLCONV callconv;
- public Int16 cParams; //short cParams;
- public Int16 cParamsOpt; //short cParamsOpt;
- public Int16 oVft; //short oVft;
- public Int16 cScodes; //short cScodes;
- public ELEMDESC elemdescFunc; //ELEMDESC elemdescFunc;
- public Int16 wFuncFlags; //WORD wFuncFlags;
- }
-
- [Obsolete("Use System.Runtime.InteropServices.ComTypes.IDLFLAG instead. http://go.microsoft.com/fwlink/?linkid=14202", false)]
-[Serializable]
-[Flags()]
- public enum IDLFLAG : short
- {
- IDLFLAG_NONE = PARAMFLAG.PARAMFLAG_NONE,
- IDLFLAG_FIN = PARAMFLAG.PARAMFLAG_FIN,
- IDLFLAG_FOUT = PARAMFLAG.PARAMFLAG_FOUT,
- IDLFLAG_FLCID = PARAMFLAG.PARAMFLAG_FLCID,
- IDLFLAG_FRETVAL = PARAMFLAG.PARAMFLAG_FRETVAL
- }
-
- [Obsolete("Use System.Runtime.InteropServices.ComTypes.IDLDESC instead. http://go.microsoft.com/fwlink/?linkid=14202", false)]
- [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
- public struct IDLDESC
- {
- public int dwReserved;
- public IDLFLAG wIDLFlags;
- }
-
- [Obsolete("Use System.Runtime.InteropServices.ComTypes.PARAMFLAG instead. http://go.microsoft.com/fwlink/?linkid=14202", false)]
-[Serializable]
-[Flags()]
- public enum PARAMFLAG :short
- {
- PARAMFLAG_NONE = 0,
- PARAMFLAG_FIN = 0x1,
- PARAMFLAG_FOUT = 0x2,
- PARAMFLAG_FLCID = 0x4,
- PARAMFLAG_FRETVAL = 0x8,
- PARAMFLAG_FOPT = 0x10,
- PARAMFLAG_FHASDEFAULT = 0x20,
- PARAMFLAG_FHASCUSTDATA = 0x40
- }
-
- [Obsolete("Use System.Runtime.InteropServices.ComTypes.PARAMDESC instead. http://go.microsoft.com/fwlink/?linkid=14202", false)]
- [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
- public struct PARAMDESC
- {
- public IntPtr lpVarValue;
- public PARAMFLAG wParamFlags;
- }
-
- [Obsolete("Use System.Runtime.InteropServices.ComTypes.TYPEDESC instead. http://go.microsoft.com/fwlink/?linkid=14202", false)]
- [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
- public struct TYPEDESC
- {
- public IntPtr lpValue;
- public Int16 vt;
- }
-
- [Obsolete("Use System.Runtime.InteropServices.ComTypes.ELEMDESC instead. http://go.microsoft.com/fwlink/?linkid=14202", false)]
- [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
- public struct ELEMDESC
- {
- public TYPEDESC tdesc;
-
- [System.Runtime.InteropServices.StructLayout(LayoutKind.Explicit, CharSet=CharSet.Unicode)]
- [ComVisible(false)]
- public struct DESCUNION
- {
- [FieldOffset(0)]
- public IDLDESC idldesc;
- [FieldOffset(0)]
- public PARAMDESC paramdesc;
- };
- public DESCUNION desc;
- }
-
- [Obsolete("Use System.Runtime.InteropServices.ComTypes.VARDESC instead. http://go.microsoft.com/fwlink/?linkid=14202", false)]
- [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
- public struct VARDESC
- {
- public int memid;
- public String lpstrSchema;
-
- [System.Runtime.InteropServices.StructLayout(LayoutKind.Explicit, CharSet=CharSet.Unicode)]
- [ComVisible(false)]
- public struct DESCUNION
- {
- [FieldOffset(0)]
- public int oInst;
- [FieldOffset(0)]
- public IntPtr lpvarValue;
- };
-
- public ELEMDESC elemdescVar;
- public short wVarFlags;
- public VarEnum varkind;
- }
-
- [Obsolete("Use System.Runtime.InteropServices.ComTypes.DISPPARAMS instead. http://go.microsoft.com/fwlink/?linkid=14202", false)]
- [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
- public struct DISPPARAMS
- {
- public IntPtr rgvarg;
- public IntPtr rgdispidNamedArgs;
- public int cArgs;
- public int cNamedArgs;
- }
-
- [Obsolete("Use System.Runtime.InteropServices.ComTypes.EXCEPINFO instead. http://go.microsoft.com/fwlink/?linkid=14202", false)]
- [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
- public struct EXCEPINFO
- {
- public Int16 wCode;
- public Int16 wReserved;
- [MarshalAs(UnmanagedType.BStr)] public String bstrSource;
- [MarshalAs(UnmanagedType.BStr)] public String bstrDescription;
- [MarshalAs(UnmanagedType.BStr)] public String bstrHelpFile;
- public int dwHelpContext;
- public IntPtr pvReserved;
- public IntPtr pfnDeferredFillIn;
- }
-
- [Obsolete("Use System.Runtime.InteropServices.ComTypes.FUNCKIND instead. http://go.microsoft.com/fwlink/?linkid=14202", false)]
- [Serializable]
- public enum FUNCKIND : int
- {
- FUNC_VIRTUAL = 0,
- FUNC_PUREVIRTUAL = 1,
- FUNC_NONVIRTUAL = 2,
- FUNC_STATIC = 3,
- FUNC_DISPATCH = 4
- }
-
- [Obsolete("Use System.Runtime.InteropServices.ComTypes.INVOKEKIND instead. http://go.microsoft.com/fwlink/?linkid=14202", false)]
- [Serializable]
- public enum INVOKEKIND : int
- {
- INVOKE_FUNC = 0x1,
- INVOKE_PROPERTYGET = 0x2,
- INVOKE_PROPERTYPUT = 0x4,
- INVOKE_PROPERTYPUTREF = 0x8
- }
-
- [Obsolete("Use System.Runtime.InteropServices.ComTypes.CALLCONV instead. http://go.microsoft.com/fwlink/?linkid=14202", false)]
- [Serializable]
- public enum CALLCONV : int
- {
- CC_CDECL =1,
- CC_MSCPASCAL=2,
- CC_PASCAL =CC_MSCPASCAL,
- CC_MACPASCAL=3,
- CC_STDCALL =4,
- CC_RESERVED =5,
- CC_SYSCALL =6,
- CC_MPWCDECL =7,
- CC_MPWPASCAL=8,
- CC_MAX =9
- }
-
- [Obsolete("Use System.Runtime.InteropServices.ComTypes.FUNCFLAGS instead. http://go.microsoft.com/fwlink/?linkid=14202", false)]
-[Serializable]
-[Flags()]
- public enum FUNCFLAGS : short
- {
- FUNCFLAG_FRESTRICTED= 0x1,
- FUNCFLAG_FSOURCE = 0x2,
- FUNCFLAG_FBINDABLE = 0x4,
- FUNCFLAG_FREQUESTEDIT = 0x8,
- FUNCFLAG_FDISPLAYBIND = 0x10,
- FUNCFLAG_FDEFAULTBIND = 0x20,
- FUNCFLAG_FHIDDEN = 0x40,
- FUNCFLAG_FUSESGETLASTERROR= 0x80,
- FUNCFLAG_FDEFAULTCOLLELEM= 0x100,
- FUNCFLAG_FUIDEFAULT = 0x200,
- FUNCFLAG_FNONBROWSABLE = 0x400,
- FUNCFLAG_FREPLACEABLE = 0x800,
- FUNCFLAG_FIMMEDIATEBIND = 0x1000
- }
-
- [Obsolete("Use System.Runtime.InteropServices.ComTypes.VARFLAGS instead. http://go.microsoft.com/fwlink/?linkid=14202", false)]
-[Serializable]
-[Flags()]
- public enum VARFLAGS : short
- {
- VARFLAG_FREADONLY =0x1,
- VARFLAG_FSOURCE =0x2,
- VARFLAG_FBINDABLE =0x4,
- VARFLAG_FREQUESTEDIT =0x8,
- VARFLAG_FDISPLAYBIND =0x10,
- VARFLAG_FDEFAULTBIND =0x20,
- VARFLAG_FHIDDEN =0x40,
- VARFLAG_FRESTRICTED =0x80,
- VARFLAG_FDEFAULTCOLLELEM =0x100,
- VARFLAG_FUIDEFAULT =0x200,
- VARFLAG_FNONBROWSABLE =0x400,
- VARFLAG_FREPLACEABLE =0x800,
- VARFLAG_FIMMEDIATEBIND =0x1000
- }
-
- [Obsolete("Use System.Runtime.InteropServices.ComTypes.ITypeInfo instead. http://go.microsoft.com/fwlink/?linkid=14202", false)]
- [Guid("00020401-0000-0000-C000-000000000046")]
- [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
- [ComImport]
- public interface UCOMITypeInfo
- {
- void GetTypeAttr(out IntPtr ppTypeAttr);
- void GetTypeComp(out UCOMITypeComp ppTComp);
- void GetFuncDesc(int index, out IntPtr ppFuncDesc);
- void GetVarDesc(int index, out IntPtr ppVarDesc);
- void GetNames(int memid, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2), Out] String[] rgBstrNames, int cMaxNames, out int pcNames);
- void GetRefTypeOfImplType(int index, out int href);
- void GetImplTypeFlags(int index, out int pImplTypeFlags);
- void GetIDsOfNames([MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.LPWStr, SizeParamIndex = 1), In] String[] rgszNames, int cNames, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1), Out] int[] pMemId);
- void Invoke([MarshalAs(UnmanagedType.IUnknown)] Object pvInstance, int memid, Int16 wFlags, ref DISPPARAMS pDispParams, out Object pVarResult, out EXCEPINFO pExcepInfo, out int puArgErr);
- void GetDocumentation(int index, out String strName, out String strDocString, out int dwHelpContext, out String strHelpFile);
- void GetDllEntry(int memid, INVOKEKIND invKind, out String pBstrDllName, out String pBstrName, out Int16 pwOrdinal);
- void GetRefTypeInfo(int hRef, out UCOMITypeInfo ppTI);
- void AddressOfMember(int memid, INVOKEKIND invKind, out IntPtr ppv);
- void CreateInstance([MarshalAs(UnmanagedType.IUnknown)] Object pUnkOuter, ref Guid riid, [MarshalAs(UnmanagedType.IUnknown), Out] out Object ppvObj);
- void GetMops(int memid, out String pBstrMops);
- void GetContainingTypeLib(out UCOMITypeLib ppTLB, out int pIndex);
- void ReleaseTypeAttr(IntPtr pTypeAttr);
- void ReleaseFuncDesc(IntPtr pFuncDesc);
- void ReleaseVarDesc(IntPtr pVarDesc);
- }
-}
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-/*=============================================================================
-**
-**
-**
-** Purpose: UCOMITypeLib interface definition.
-**
-**
-=============================================================================*/
-
-namespace System.Runtime.InteropServices
-{
- using System;
-
- [Obsolete("Use System.Runtime.InteropServices.ComTypes.SYSKIND instead. http://go.microsoft.com/fwlink/?linkid=14202", false)]
- [Serializable]
- public enum SYSKIND
- {
- SYS_WIN16 = 0,
- SYS_WIN32 = SYS_WIN16 + 1,
- SYS_MAC = SYS_WIN32 + 1
- }
-
- [Obsolete("Use System.Runtime.InteropServices.ComTypes.LIBFLAGS instead. http://go.microsoft.com/fwlink/?linkid=14202", false)]
-[Serializable]
-[Flags()]
- public enum LIBFLAGS : short
- {
- LIBFLAG_FRESTRICTED = 0x1,
- LIBFLAG_FCONTROL = 0x2,
- LIBFLAG_FHIDDEN = 0x4,
- LIBFLAG_FHASDISKIMAGE = 0x8
- }
-
- [Obsolete("Use System.Runtime.InteropServices.ComTypes.TYPELIBATTR instead. http://go.microsoft.com/fwlink/?linkid=14202", false)]
- [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
- [Serializable]
- public struct TYPELIBATTR
- {
- public Guid guid;
- public int lcid;
- public SYSKIND syskind;
- public Int16 wMajorVerNum;
- public Int16 wMinorVerNum;
- public LIBFLAGS wLibFlags;
- }
-
- [Obsolete("Use System.Runtime.InteropServices.ComTypes.ITypeLib instead. http://go.microsoft.com/fwlink/?linkid=14202", false)]
- [Guid("00020402-0000-0000-C000-000000000046")]
- [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
- [ComImport]
- public interface UCOMITypeLib
- {
- [PreserveSig]
- int GetTypeInfoCount();
- void GetTypeInfo(int index, out UCOMITypeInfo ppTI);
- void GetTypeInfoType(int index, out TYPEKIND pTKind);
- void GetTypeInfoOfGuid(ref Guid guid, out UCOMITypeInfo ppTInfo);
- void GetLibAttr(out IntPtr ppTLibAttr);
- void GetTypeComp(out UCOMITypeComp ppTComp);
- void GetDocumentation(int index, out String strName, out String strDocString, out int dwHelpContext, out String strHelpFile);
- [return : MarshalAs(UnmanagedType.Bool)]
- bool IsName([MarshalAs(UnmanagedType.LPWStr)] String szNameBuf, int lHashVal);
- void FindName([MarshalAs(UnmanagedType.LPWStr)] String szNameBuf, int lHashVal, [MarshalAs(UnmanagedType.LPArray), Out] UCOMITypeInfo[] ppTInfo, [MarshalAs(UnmanagedType.LPArray), Out] int[] rgMemId, ref Int16 pcFound);
- [PreserveSig]
- void ReleaseTLibAttr(IntPtr pTLibAttr);
- }
-}
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-namespace System.Runtime.InteropServices {
- using System.Diagnostics;
-
- /// <summary>
- /// Variant is the basic COM type for late-binding. It can contain any other COM data type.
- /// This type definition precisely matches the unmanaged data layout so that the struct can be passed
- /// to and from COM calls.
- /// </summary>
- [StructLayout(LayoutKind.Explicit)]
- internal struct Variant {
-
-#if DEBUG
- static Variant() {
- // Variant size is the size of 4 pointers (16 bytes) on a 32-bit processor,
- // and 3 pointers (24 bytes) on a 64-bit processor.
- int variantSize = Marshal.SizeOf(typeof(Variant));
- if (IntPtr.Size == 4) {
- BCLDebug.Assert(variantSize == (4 * IntPtr.Size), "variant");
- } else {
- BCLDebug.Assert(IntPtr.Size == 8, "variant");
- BCLDebug.Assert(variantSize == (3 * IntPtr.Size), "variant");
- }
- }
-#endif
-
- // Most of the data types in the Variant are carried in _typeUnion
- [FieldOffset(0)] private TypeUnion _typeUnion;
-
- // Decimal is the largest data type and it needs to use the space that is normally unused in TypeUnion._wReserved1, etc.
- // Hence, it is declared to completely overlap with TypeUnion. A Decimal does not use the first two bytes, and so
- // TypeUnion._vt can still be used to encode the type.
- [FieldOffset(0)] private Decimal _decimal;
-
- [StructLayout(LayoutKind.Sequential)]
- private struct TypeUnion {
- internal ushort _vt;
- internal ushort _wReserved1;
- internal ushort _wReserved2;
- internal ushort _wReserved3;
-
- internal UnionTypes _unionTypes;
- }
-
- [StructLayout(LayoutKind.Sequential)]
- private struct Record {
- private IntPtr _record;
- private IntPtr _recordInfo;
- }
-
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1049:TypesThatOwnNativeResourcesShouldBeDisposable")]
- [StructLayout(LayoutKind.Explicit)]
- private struct UnionTypes {
- #region Generated Variant union types
-
- // *** BEGIN GENERATED CODE ***
- // generated by function: gen_UnionTypes from: generate_comdispatch.py
-
- [FieldOffset(0)] internal SByte _i1;
- [FieldOffset(0)] internal Int16 _i2;
- [FieldOffset(0)] internal Int32 _i4;
- [FieldOffset(0)] internal Int64 _i8;
- [FieldOffset(0)] internal Byte _ui1;
- [FieldOffset(0)] internal UInt16 _ui2;
- [FieldOffset(0)] internal UInt32 _ui4;
- [FieldOffset(0)] internal UInt64 _ui8;
- [FieldOffset(0)] internal Int32 _int;
- [FieldOffset(0)] internal UInt32 _uint;
- [FieldOffset(0)] internal Int16 _bool;
- [FieldOffset(0)] internal Int32 _error;
- [FieldOffset(0)] internal Single _r4;
- [FieldOffset(0)] internal Double _r8;
- [FieldOffset(0)] internal Int64 _cy;
- [FieldOffset(0)] internal double _date;
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")]
- [FieldOffset(0)] internal IntPtr _bstr;
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")]
- [FieldOffset(0)] internal IntPtr _unknown;
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")]
- [FieldOffset(0)] internal IntPtr _dispatch;
-
- // *** END GENERATED CODE ***
-
- #endregion
-
- [FieldOffset(0)] internal IntPtr _pvarVal;
- [FieldOffset(0)] internal IntPtr _byref;
- [FieldOffset(0)] internal Record _record;
- }
-
- /// <summary>
- /// Primitive types are the basic COM types. It includes valuetypes like ints, but also reference types
- /// like BStrs. It does not include composite types like arrays and user-defined COM types (IUnknown/IDispatch).
- /// </summary>
- internal static bool IsPrimitiveType(VarEnum varEnum) {
- switch(varEnum) {
- #region Generated Variant IsPrimitiveType
-
- // *** BEGIN GENERATED CODE ***
- // generated by function: gen_IsPrimitiveType from: generate_comdispatch.py
-
- case VarEnum.VT_I1:
- case VarEnum.VT_I2:
- case VarEnum.VT_I4:
- case VarEnum.VT_I8:
- case VarEnum.VT_UI1:
- case VarEnum.VT_UI2:
- case VarEnum.VT_UI4:
- case VarEnum.VT_UI8:
- case VarEnum.VT_INT:
- case VarEnum.VT_UINT:
- case VarEnum.VT_BOOL:
- case VarEnum.VT_R4:
- case VarEnum.VT_R8:
- case VarEnum.VT_DECIMAL:
- case VarEnum.VT_DATE:
- case VarEnum.VT_BSTR:
-
- // *** END GENERATED CODE ***
-
- #endregion
- return true;
- }
-
- return false;
- }
-
- unsafe public void CopyFromIndirect(object value) {
-
- VarEnum vt = (VarEnum)(((int)this.VariantType) & ~((int)VarEnum.VT_BYREF));
-
- if (value == null) {
- if (vt == VarEnum.VT_DISPATCH || vt == VarEnum.VT_UNKNOWN || vt == VarEnum.VT_BSTR) {
- *(IntPtr*)this._typeUnion._unionTypes._byref = IntPtr.Zero;
- }
- return;
- }
-
- switch (vt) {
- case VarEnum.VT_I1:
- *(sbyte*)this._typeUnion._unionTypes._byref = (sbyte)value;
- break;
-
- case VarEnum.VT_UI1:
- *(byte*)this._typeUnion._unionTypes._byref = (byte)value;
- break;
-
- case VarEnum.VT_I2:
- *(short*)this._typeUnion._unionTypes._byref = (short)value;
- break;
-
- case VarEnum.VT_UI2:
- *(ushort*)this._typeUnion._unionTypes._byref = (ushort)value;
- break;
-
- case VarEnum.VT_BOOL:
- *(short*)this._typeUnion._unionTypes._byref = (bool)value ? (short)-1 : (short)0;
- break;
-
- case VarEnum.VT_I4:
- case VarEnum.VT_INT:
- *(int*)this._typeUnion._unionTypes._byref = (int)value;
- break;
-
- case VarEnum.VT_UI4:
- case VarEnum.VT_UINT:
- *(uint*)this._typeUnion._unionTypes._byref = (uint)value;
- break;
-
- case VarEnum.VT_ERROR:
- *(int*)this._typeUnion._unionTypes._byref = ((ErrorWrapper)value).ErrorCode;
- break;
-
- case VarEnum.VT_I8:
- *(Int64*)this._typeUnion._unionTypes._byref = (Int64)value;
- break;
-
- case VarEnum.VT_UI8:
- *(UInt64*)this._typeUnion._unionTypes._byref = (UInt64)value;
- break;
-
- case VarEnum.VT_R4:
- *(float*)this._typeUnion._unionTypes._byref = (float)value;
- break;
-
- case VarEnum.VT_R8:
- *(double*)this._typeUnion._unionTypes._byref = (double)value;
- break;
-
- case VarEnum.VT_DATE:
- *(double*)this._typeUnion._unionTypes._byref = ((DateTime)value).ToOADate();
- break;
-
- case VarEnum.VT_UNKNOWN:
- *(IntPtr*)this._typeUnion._unionTypes._byref = Marshal.GetIUnknownForObject(value);
- break;
-
- case VarEnum.VT_DISPATCH:
- *(IntPtr*)this._typeUnion._unionTypes._byref = Marshal.GetIDispatchForObject(value);
- break;
-
- case VarEnum.VT_BSTR:
- *(IntPtr*)this._typeUnion._unionTypes._byref = Marshal.StringToBSTR((string)value);
- break;
-
- case VarEnum.VT_CY:
- *(long*)this._typeUnion._unionTypes._byref = decimal.ToOACurrency((decimal)value);
- break;
-
- case VarEnum.VT_DECIMAL:
- *(decimal*)this._typeUnion._unionTypes._byref = (decimal)value;
- break;
-
- case VarEnum.VT_VARIANT:
- Marshal.GetNativeVariantForObject(value, this._typeUnion._unionTypes._byref);
- break;
-
- default:
- throw new ArgumentException("invalid argument type");
- }
- }
-
- /// <summary>
- /// Get the managed object representing the Variant.
- /// </summary>
- /// <returns></returns>
- public object ToObject() {
- // Check the simple case upfront
- if (IsEmpty) {
- return null;
- }
-
- switch (VariantType) {
- case VarEnum.VT_NULL: return DBNull.Value;
-
- #region Generated Variant ToObject
-
- // *** BEGIN GENERATED CODE ***
- // generated by function: gen_ToObject from: generate_comdispatch.py
-
- case VarEnum.VT_I1: return AsI1;
- case VarEnum.VT_I2: return AsI2;
- case VarEnum.VT_I4: return AsI4;
- case VarEnum.VT_I8: return AsI8;
- case VarEnum.VT_UI1: return AsUi1;
- case VarEnum.VT_UI2: return AsUi2;
- case VarEnum.VT_UI4: return AsUi4;
- case VarEnum.VT_UI8: return AsUi8;
- case VarEnum.VT_INT: return AsInt;
- case VarEnum.VT_UINT: return AsUint;
- case VarEnum.VT_BOOL: return AsBool;
- case VarEnum.VT_ERROR: return AsError;
- case VarEnum.VT_R4: return AsR4;
- case VarEnum.VT_R8: return AsR8;
- case VarEnum.VT_DECIMAL: return AsDecimal;
- case VarEnum.VT_CY: return AsCy;
- case VarEnum.VT_DATE: return AsDate;
- case VarEnum.VT_BSTR: return AsBstr;
- case VarEnum.VT_UNKNOWN: return AsUnknown;
- case VarEnum.VT_DISPATCH: return AsDispatch;
- // VarEnum.VT_VARIANT is handled by Marshal.GetObjectForNativeVariant below
-
- // *** END GENERATED CODE ***
-
- #endregion
-
- default:
- try {
- unsafe {
- fixed (void* pThis = &this) {
- return Marshal.GetObjectForNativeVariant((System.IntPtr)pThis);
- }
- }
- }
- catch (Exception ex) {
- throw new NotImplementedException("Variant.ToObject cannot handle" + VariantType, ex);
- }
- }
- }
-
- /// <summary>
- /// Release any unmanaged memory associated with the Variant
- /// </summary>
- /// <returns></returns>
- public void Clear() {
- // We do not need to call OLE32's VariantClear for primitive types or ByRefs
- // to safe ourselves the cost of interop transition.
- // ByRef indicates the memory is not owned by the VARIANT itself while
- // primitive types do not have any resources to free up.
- // Hence, only safearrays, BSTRs, interfaces and user types are
- // handled differently.
- VarEnum vt = VariantType;
- if ((vt & VarEnum.VT_BYREF) != 0) {
- VariantType = VarEnum.VT_EMPTY;
- } else if (
- ((vt & VarEnum.VT_ARRAY) != 0) ||
- ((vt) == VarEnum.VT_BSTR) ||
- ((vt) == VarEnum.VT_UNKNOWN) ||
- ((vt) == VarEnum.VT_DISPATCH) ||
- ((vt) == VarEnum.VT_VARIANT) ||
- ((vt) == VarEnum.VT_RECORD) ||
- ((vt) == VarEnum.VT_VARIANT)
- ) {
- unsafe {
- fixed (void* pThis = &this) {
- NativeMethods.VariantClear((IntPtr)pThis);
- }
- }
- BCLDebug.Assert(IsEmpty, "variant");
- } else {
- VariantType = VarEnum.VT_EMPTY;
- }
- }
-
- public VarEnum VariantType {
- get {
- return (VarEnum)_typeUnion._vt;
- }
- set {
- _typeUnion._vt = (ushort)value;
- }
- }
-
- internal bool IsEmpty {
- get {
- return _typeUnion._vt == ((ushort)VarEnum.VT_EMPTY);
- }
- }
-
- internal bool IsByRef {
- get {
- return (_typeUnion._vt & ((ushort)VarEnum.VT_BYREF)) != 0;
- }
- }
-
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")]
- public void SetAsNULL() {
- BCLDebug.Assert(IsEmpty, "variant"); // The setter can only be called once as VariantClear might be needed otherwise
- VariantType = VarEnum.VT_NULL;
- }
-
- #region Generated Variant accessors
-
- // *** BEGIN GENERATED CODE ***
- // generated by function: gen_accessors from: generate_comdispatch.py
-
- // VT_I1
-
- public SByte AsI1 {
- get {
- BCLDebug.Assert(VariantType == VarEnum.VT_I1, "variant");
- return _typeUnion._unionTypes._i1;
- }
- set {
- BCLDebug.Assert(IsEmpty, "variant"); // The setter can only be called once as VariantClear might be needed otherwise
- VariantType = VarEnum.VT_I1;
- _typeUnion._unionTypes._i1 = value;
- }
- }
-
- // VT_I2
-
- public Int16 AsI2 {
- get {
- BCLDebug.Assert(VariantType == VarEnum.VT_I2, "variant");
- return _typeUnion._unionTypes._i2;
- }
- set {
- BCLDebug.Assert(IsEmpty, "variant"); // The setter can only be called once as VariantClear might be needed otherwise
- VariantType = VarEnum.VT_I2;
- _typeUnion._unionTypes._i2 = value;
- }
- }
-
- // VT_I4
-
- public Int32 AsI4 {
- get {
- BCLDebug.Assert(VariantType == VarEnum.VT_I4, "variant");
- return _typeUnion._unionTypes._i4;
- }
- set {
- BCLDebug.Assert(IsEmpty, "variant"); // The setter can only be called once as VariantClear might be needed otherwise
- VariantType = VarEnum.VT_I4;
- _typeUnion._unionTypes._i4 = value;
- }
- }
-
- // VT_I8
-
- public Int64 AsI8 {
- get {
- BCLDebug.Assert(VariantType == VarEnum.VT_I8, "variant");
- return _typeUnion._unionTypes._i8;
- }
- set {
- BCLDebug.Assert(IsEmpty, "variant"); // The setter can only be called once as VariantClear might be needed otherwise
- VariantType = VarEnum.VT_I8;
- _typeUnion._unionTypes._i8 = value;
- }
- }
-
- // VT_UI1
-
- public Byte AsUi1 {
- get {
- BCLDebug.Assert(VariantType == VarEnum.VT_UI1, "variant");
- return _typeUnion._unionTypes._ui1;
- }
- set {
- BCLDebug.Assert(IsEmpty, "variant"); // The setter can only be called once as VariantClear might be needed otherwise
- VariantType = VarEnum.VT_UI1;
- _typeUnion._unionTypes._ui1 = value;
- }
- }
-
- // VT_UI2
-
- public UInt16 AsUi2 {
- get {
- BCLDebug.Assert(VariantType == VarEnum.VT_UI2, "variant");
- return _typeUnion._unionTypes._ui2;
- }
- set {
- BCLDebug.Assert(IsEmpty, "variant"); // The setter can only be called once as VariantClear might be needed otherwise
- VariantType = VarEnum.VT_UI2;
- _typeUnion._unionTypes._ui2 = value;
- }
- }
-
- // VT_UI4
-
- public UInt32 AsUi4 {
- get {
- BCLDebug.Assert(VariantType == VarEnum.VT_UI4, "variant");
- return _typeUnion._unionTypes._ui4;
- }
- set {
- BCLDebug.Assert(IsEmpty, "variant"); // The setter can only be called once as VariantClear might be needed otherwise
- VariantType = VarEnum.VT_UI4;
- _typeUnion._unionTypes._ui4 = value;
- }
- }
-
- // VT_UI8
-
- public UInt64 AsUi8 {
- get {
- BCLDebug.Assert(VariantType == VarEnum.VT_UI8, "variant");
- return _typeUnion._unionTypes._ui8;
- }
- set {
- BCLDebug.Assert(IsEmpty, "variant"); // The setter can only be called once as VariantClear might be needed otherwise
- VariantType = VarEnum.VT_UI8;
- _typeUnion._unionTypes._ui8 = value;
- }
- }
-
- // VT_INT
-
- public Int32 AsInt {
- get {
- BCLDebug.Assert(VariantType == VarEnum.VT_INT, "variant");
- return _typeUnion._unionTypes._int;
- }
- set {
- BCLDebug.Assert(IsEmpty, "variant"); // The setter can only be called once as VariantClear might be needed otherwise
- VariantType = VarEnum.VT_INT;
- _typeUnion._unionTypes._int = value;
- }
- }
-
- // VT_UINT
-
- public UInt32 AsUint {
- get {
- BCLDebug.Assert(VariantType == VarEnum.VT_UINT, "variant");
- return _typeUnion._unionTypes._uint;
- }
- set {
- BCLDebug.Assert(IsEmpty, "variant"); // The setter can only be called once as VariantClear might be needed otherwise
- VariantType = VarEnum.VT_UINT;
- _typeUnion._unionTypes._uint = value;
- }
- }
-
- // VT_BOOL
-
- public bool AsBool {
- get {
- BCLDebug.Assert(VariantType == VarEnum.VT_BOOL, "variant");
- return _typeUnion._unionTypes._bool != 0;
- }
- set {
- BCLDebug.Assert(IsEmpty, "variant"); // The setter can only be called once as VariantClear might be needed otherwise
- VariantType = VarEnum.VT_BOOL;
- _typeUnion._unionTypes._bool = value ? (short)-1 : (short)0;
- }
- }
-
- // VT_ERROR
-
- public Int32 AsError {
- get {
- BCLDebug.Assert(VariantType == VarEnum.VT_ERROR, "variant");
- return _typeUnion._unionTypes._error;
- }
- set {
- BCLDebug.Assert(IsEmpty, "variant"); // The setter can only be called once as VariantClear might be needed otherwise
- VariantType = VarEnum.VT_ERROR;
- _typeUnion._unionTypes._error = value;
- }
- }
-
- // VT_R4
-
- public Single AsR4 {
- get {
- BCLDebug.Assert(VariantType == VarEnum.VT_R4, "variant");
- return _typeUnion._unionTypes._r4;
- }
- set {
- BCLDebug.Assert(IsEmpty, "variant"); // The setter can only be called once as VariantClear might be needed otherwise
- VariantType = VarEnum.VT_R4;
- _typeUnion._unionTypes._r4 = value;
- }
- }
-
- // VT_R8
-
- public Double AsR8 {
- get {
- BCLDebug.Assert(VariantType == VarEnum.VT_R8, "variant");
- return _typeUnion._unionTypes._r8;
- }
- set {
- BCLDebug.Assert(IsEmpty, "variant"); // The setter can only be called once as VariantClear might be needed otherwise
- VariantType = VarEnum.VT_R8;
- _typeUnion._unionTypes._r8 = value;
- }
- }
-
- // VT_DECIMAL
-
- public Decimal AsDecimal {
- get {
- BCLDebug.Assert(VariantType == VarEnum.VT_DECIMAL, "variant");
- // The first byte of Decimal is unused, but usually set to 0
- Variant v = this;
- v._typeUnion._vt = 0;
- return v._decimal;
- }
- set {
- BCLDebug.Assert(IsEmpty, "variant"); // The setter can only be called once as VariantClear might be needed otherwise
- VariantType = VarEnum.VT_DECIMAL;
- _decimal = value;
- // _vt overlaps with _decimal, and should be set after setting _decimal
- _typeUnion._vt = (ushort)VarEnum.VT_DECIMAL;
- }
- }
-
- // VT_CY
-
- public Decimal AsCy {
- get {
- BCLDebug.Assert(VariantType == VarEnum.VT_CY, "variant");
- return Decimal.FromOACurrency(_typeUnion._unionTypes._cy);
- }
- set {
- BCLDebug.Assert(IsEmpty, "variant"); // The setter can only be called once as VariantClear might be needed otherwise
- VariantType = VarEnum.VT_CY;
- _typeUnion._unionTypes._cy = Decimal.ToOACurrency(value);
- }
- }
-
- // VT_DATE
-
- public DateTime AsDate {
- get {
- BCLDebug.Assert(VariantType == VarEnum.VT_DATE, "variant");
- return DateTime.FromOADate(_typeUnion._unionTypes._date);
- }
- set {
- BCLDebug.Assert(IsEmpty, "variant"); // The setter can only be called once as VariantClear might be needed otherwise
- VariantType = VarEnum.VT_DATE;
- _typeUnion._unionTypes._date = value.ToOADate();
- }
- }
-
- // VT_BSTR
-
- public String AsBstr {
- get {
- BCLDebug.Assert(VariantType == VarEnum.VT_BSTR, "variant");
- return (string)Marshal.PtrToStringBSTR(this._typeUnion._unionTypes._bstr);
- }
- set {
- BCLDebug.Assert(IsEmpty, "variant"); // The setter can only be called once as VariantClear might be needed otherwise
- VariantType = VarEnum.VT_BSTR;
- this._typeUnion._unionTypes._bstr = Marshal.StringToBSTR(value);
- }
- }
-
- // VT_UNKNOWN
-
- public Object AsUnknown {
- get {
- BCLDebug.Assert(VariantType == VarEnum.VT_UNKNOWN, "variant");
- if (_typeUnion._unionTypes._unknown == IntPtr.Zero)
- return null;
- return Marshal.GetObjectForIUnknown(_typeUnion._unionTypes._unknown);
- }
- set {
- BCLDebug.Assert(IsEmpty, "variant"); // The setter can only be called once as VariantClear might be needed otherwise
- VariantType = VarEnum.VT_UNKNOWN;
- if (value == null)
- _typeUnion._unionTypes._unknown = IntPtr.Zero;
- else
- _typeUnion._unionTypes._unknown = Marshal.GetIUnknownForObject(value);
- }
- }
-
- // VT_DISPATCH
-
- public Object AsDispatch {
- get {
- BCLDebug.Assert(VariantType == VarEnum.VT_DISPATCH, "variant");
- if (_typeUnion._unionTypes._dispatch == IntPtr.Zero)
- return null;
- return Marshal.GetObjectForIUnknown(_typeUnion._unionTypes._dispatch);
- }
- set {
- BCLDebug.Assert(IsEmpty, "variant"); // The setter can only be called once as VariantClear might be needed otherwise
- VariantType = VarEnum.VT_DISPATCH;
- if (value == null)
- _typeUnion._unionTypes._dispatch = IntPtr.Zero;
- else
- _typeUnion._unionTypes._dispatch = Marshal.GetIDispatchForObject(value);
- }
- }
-
-
- // *** END GENERATED CODE ***
-
- internal IntPtr AsByRefVariant
- {
- get {
- BCLDebug.Assert(VariantType == (VarEnum.VT_BYREF | VarEnum.VT_VARIANT), "variant");
- return _typeUnion._unionTypes._pvarVal;
- }
- }
-
- #endregion
- }
-}
FCFuncElement("GetNativeActivationFactory", MarshalNative::GetNativeActivationFactory)
FCFuncElement("GetIUnknownForObjectNative", MarshalNative::GetIUnknownForObjectNative)
+#ifndef FEATURE_CORECLR
FCFuncElement("GetIDispatchForObjectNative", MarshalNative::GetIDispatchForObjectNative)
+#endif // FEATURE_CORECLR
FCFuncElement("GetComInterfaceForObjectNative", MarshalNative::GetComInterfaceForObjectNative)
FCFuncElement("InternalReleaseComObject", MarshalNative::ReleaseComObject)
FCFuncElement("Release", MarshalNative::Release)