Beispiel #1
0
        private MethodIL EmitIL()
        {
            if (!_importMetadata.Flags.PreserveSig)
            {
                throw new NotSupportedException();
            }

            if (MarshalHelpers.ShouldCheckForPendingException(_targetMethod.Context.Target, _importMetadata))
            {
                throw new NotSupportedException();
            }

            if (_targetMethod.IsUnmanagedCallersOnly)
            {
                throw new NotSupportedException();
            }

            if (_targetMethod.HasCustomAttribute("System.Runtime.InteropServices", "LCIDConversionAttribute"))
            {
                throw new NotSupportedException();
            }

            PInvokeILCodeStreams pInvokeILCodeStreams = new PInvokeILCodeStreams();
            ILEmitter            emitter = pInvokeILCodeStreams.Emitter;
            ILCodeStream         marshallingCodestream   = pInvokeILCodeStreams.MarshallingCodeStream;
            ILCodeStream         unmarshallingCodestream = pInvokeILCodeStreams.UnmarshallingCodestream;
            ILCodeStream         cleanupCodestream       = pInvokeILCodeStreams.CleanupCodeStream;

            // Marshalling is wrapped in a finally block to guarantee cleanup
            ILExceptionRegionBuilder tryFinally = emitter.NewFinallyRegion();

            marshallingCodestream.BeginTry(tryFinally);
            cleanupCodestream.BeginHandler(tryFinally);

            // Marshal the arguments
            for (int i = 0; i < _marshallers.Length; i++)
            {
                _marshallers[i].EmitMarshallingIL(pInvokeILCodeStreams);
            }

            EmitPInvokeCall(pInvokeILCodeStreams);

            ILCodeLabel lReturn = emitter.NewCodeLabel();

            unmarshallingCodestream.Emit(ILOpcode.leave, lReturn);
            unmarshallingCodestream.EndTry(tryFinally);

            cleanupCodestream.Emit(ILOpcode.endfinally);
            cleanupCodestream.EndHandler(tryFinally);

            cleanupCodestream.EmitLabel(lReturn);

            _marshallers[0].LoadReturnValue(cleanupCodestream);
            cleanupCodestream.Emit(ILOpcode.ret);

            return(new PInvokeILStubMethodIL((ILStubMethodIL)emitter.Link(_targetMethod)));
        }
 public static string GetRealmPath(User user, Uri serverUri)
 {
     DoInitialFileSystemConfiguration();
     return(MarshalHelpers.GetString((IntPtr buffer, IntPtr bufferLength, out bool isNull, out NativeException ex) =>
     {
         isNull = false;
         return NativeMethods.get_path_for_realm(user.Handle, serverUri.AbsoluteUri, (IntPtr)serverUri.AbsoluteUri.Length, buffer, bufferLength, out ex);
     }));
 }
        /// <summary>
        /// Gets a specified Mixer Control
        /// </summary>
        /// <param name="mixerHandle">Mixer Handle</param>
        /// <param name="nLineId">Line ID</param>
        /// <param name="controlId">Control ID</param>
        /// <param name="nChannels">Number of Channels</param>
        /// <param name="mixerFlags">Flags to use (indicates the meaning of mixerHandle)</param>
        /// <returns></returns>
        public static MixerControl GetMixerControl(IntPtr mixerHandle, int nLineId, int controlId, int nChannels,
                                                   MixerFlags mixerFlags)
        {
            var mlc = new MixerInterop.MIXERLINECONTROLS();
            var mc  = new MixerInterop.MIXERCONTROL();

            // set up the pointer to a structure
            IntPtr pMixerControl = Marshal.AllocCoTaskMem(Marshal.SizeOf(mc));

            //Marshal.StructureToPtr(mc, pMixerControl, false);

            mlc.cbStruct    = Marshal.SizeOf(mlc);
            mlc.cControls   = 1;
            mlc.dwControlID = controlId;
            mlc.cbmxctrl    = Marshal.SizeOf(mc);
            mlc.pamxctrl    = pMixerControl;
            mlc.dwLineID    = nLineId;
            MmResult err = MixerInterop.mixerGetLineControls(mixerHandle, ref mlc, MixerFlags.OneById | mixerFlags);

            if (err != MmResult.NoError)
            {
                Marshal.FreeCoTaskMem(pMixerControl);
                throw new MmException(err, "mixerGetLineControls");
            }

            // retrieve the structure from the pointer
            mc = MarshalHelpers.PtrToStructure <MixerInterop.MIXERCONTROL>(mlc.pamxctrl);
            Marshal.FreeCoTaskMem(pMixerControl);

            if (IsControlBoolean(mc.dwControlType))
            {
                return(new BooleanMixerControl(mc, mixerHandle, mixerFlags, nChannels));
            }

            if (IsControlSigned(mc.dwControlType))
            {
                return(new SignedMixerControl(mc, mixerHandle, mixerFlags, nChannels));
            }

            if (IsControlUnsigned(mc.dwControlType))
            {
                return(new UnsignedMixerControl(mc, mixerHandle, mixerFlags, nChannels));
            }

            if (IsControlListText(mc.dwControlType))
            {
                return(new ListTextMixerControl(mc, mixerHandle, mixerFlags, nChannels));
            }

            if (IsControlCustom(mc.dwControlType))
            {
                return(new CustomMixerControl(mc, mixerHandle, mixerFlags, nChannels));
            }

            throw new InvalidOperationException($"Unknown mixer control type {mc.dwControlType}");
        }
Beispiel #4
0
 /// <summary>
 /// Sets the parameters that describe the properties of the client's audio stream.
 /// </summary>
 /// <param name="useHardwareOffload">Boolean value to indicate whether or not the audio stream is hardware-offloaded.</param>
 /// <param name="category">An enumeration that is used to specify the category of the audio stream.</param>
 /// <param name="options">A bit-field describing the characteristics of the stream. Supported in Windows 8.1 and later.</param>
 public void SetClientProperties(bool useHardwareOffload, AudioStreamCategory category, AudioClientStreamOptions options)
 {
     audioClientProperties = new AudioClientProperties()
     {
         cbSize     = (uint)MarshalHelpers.SizeOf <AudioClientProperties>(),
         bIsOffload = Convert.ToInt32(useHardwareOffload),
         eCategory  = category,
         Options    = options
     };
 }
        private void AddDependenciesDueToPInvokeStruct(ref DependencyList dependencies, NodeFactory factory, TypeDesc type)
        {
            if (MarshalHelpers.IsStructMarshallingRequired(type))
            {
                dependencies.Add(factory.NecessaryTypeSymbol(type), "Struct Marshalling Stub");

                var stub = (StructMarshallingThunk)GetStructMarshallingManagedToNativeStub(type);
                dependencies.Add(factory.MethodEntrypoint(stub), "Struct Marshalling stub");
                dependencies.Add(factory.MethodEntrypoint(GetStructMarshallingNativeToManagedStub(type)), "Struct Marshalling stub");
                dependencies.Add(factory.MethodEntrypoint(GetStructMarshallingCleanupStub(type)), "Struct Marshalling stub");

                AddDependenciesDueToPInvokeStructDelegateField(ref dependencies, factory, type);
            }
        }
        public static UInt32 PartyXblChatUserGetCustomContext(
            PARTY_XBL_CHAT_USER_HANDLE handle,
            out Object customContext)
        {
            if (handle == null)
            {
                customContext = null;
                return(PartyError.InvalidArg);
            }

            return(MarshalHelpers.GetCustomContext <Interop.PARTY_XBL_CHAT_USER_HANDLE>(
                       PartyXblInterop.PartyXblChatUserGetCustomContext,
                       handle.InteropHandle,
                       out customContext));
        }
Beispiel #7
0
        private static void ConvertXmlToBinary(List <string> args)
        {
            if (args.Count != 2)
            {
                Console.WriteLine("infile and outfile required");
                return;
            }
            string inFile  = args[0];
            string outFile = args[1];

            WifiMp3Settings settings = ReadSettingsFromFile(inFile);

            byte[] data = MarshalHelpers.ToBytes(settings);
            File.WriteAllBytes(outFile, data);
        }
Beispiel #8
0
        private static void AddAttribute(IMFActivate mft, int index, StringBuilder sb)
        {
            var variantPtr = Marshal.AllocHGlobal(MarshalHelpers.SizeOf <PropVariant>());

            try
            {
                Guid key;
                mft.GetItemByIndex(index, out key, variantPtr);
                var    value        = MarshalHelpers.PtrToStructure <PropVariant>(variantPtr);
                string propertyName = FieldDescriptionHelper.Describe(typeof(MediaFoundationAttributes), key);
                if (key == MediaFoundationAttributes.MFT_INPUT_TYPES_Attributes ||
                    key == MediaFoundationAttributes.MFT_OUTPUT_TYPES_Attributes)
                {
                    var types = value.GetBlobAsArrayOf <MFT_REGISTER_TYPE_INFO>();
                    sb.AppendFormat("{0}: {1} items:", propertyName, types.Length);
                    sb.AppendLine();
                    foreach (var t in types)
                    {
                        sb.AppendFormat("    {0}-{1}",
                                        FieldDescriptionHelper.Describe(typeof(MediaTypes), t.guidMajorType),
                                        FieldDescriptionHelper.Describe(typeof(AudioSubtypes), t.guidSubtype));
                        sb.AppendLine();
                    }
                }
                else if (key == MediaFoundationAttributes.MF_TRANSFORM_CATEGORY_Attribute)
                {
                    sb.AppendFormat("{0}: {1}", propertyName,
                                    FieldDescriptionHelper.Describe(typeof(MediaFoundationTransformCategories), (Guid)value.Value));
                    sb.AppendLine();
                }
                else if (value.DataType == (VarEnum.VT_VECTOR | VarEnum.VT_UI1))
                {
                    var b = (byte[])value.Value;
                    sb.AppendFormat("{0}: Blob of {1} bytes", propertyName, b.Length);
                    sb.AppendLine();
                }
                else
                {
                    sb.AppendFormat("{0}: {1}", propertyName, value.Value);
                    sb.AppendLine();
                }
            }
            finally
            {
                PropVariant.Clear(variantPtr);
                Marshal.FreeHGlobal(variantPtr);
            }
        }
        public static UInt32 PartyXblGetChatUsers(
            PARTY_XBL_HANDLE handle,
            out PARTY_XBL_CHAT_USER_HANDLE[] chatUsers)
        {
            chatUsers = null;
            if (handle == null)
            {
                return(PartyError.InvalidArg);
            }

            return(MarshalHelpers.GetArrayOfObjects <Interop.PARTY_XBL_HANDLE, Interop.PARTY_XBL_CHAT_USER_HANDLE, PARTY_XBL_CHAT_USER_HANDLE>(
                       PartyXblInterop.PartyXblGetChatUsers,
                       s => new PARTY_XBL_CHAT_USER_HANDLE(s),
                       handle.InteropHandle,
                       out chatUsers));
        }
        private TypeDesc GetNativeMethodParameterType(TypeDesc managedType, MarshalAsDescriptor marshalAs, InteropStateManager interopStateManager, bool isReturn, bool isAnsi)
        {
            TypeDesc nativeType;

            try
            {
                nativeType = MarshalHelpers.GetNativeMethodParameterType(managedType, marshalAs, interopStateManager, isReturn, isAnsi);
            }
            catch (NotSupportedException)
            {
                // if marshalling is not supported for this type the generated stubs will emit appropriate
                // error message. We just set native type to be same as managedtype
                nativeType = managedType;
            }
            return(nativeType);
        }
Beispiel #11
0
        private void EmitPInvokeCall(PInvokeILCodeStreams ilCodeStreams)
        {
            ILEmitter         emitter = ilCodeStreams.Emitter;
            ILCodeStream      callsiteSetupCodeStream = ilCodeStreams.CallsiteSetupCodeStream;
            TypeSystemContext context = _targetMethod.Context;

            TypeDesc nativeReturnType = _marshallers[0].NativeParameterType;

            TypeDesc[] nativeParameterTypes = new TypeDesc[_marshallers.Length - 1];

            MetadataType stubHelpersType = InteropTypes.GetStubHelpers(context);

            // if the SetLastError flag is set in DllImport, clear the error code before doing P/Invoke
            if (_importMetadata.Flags.SetLastError)
            {
                if (!MarshalHelpers.IsRuntimeMarshallingEnabled(((MetadataType)_targetMethod.OwningType).Module))
                {
                    // When runtime marshalling is disabled, we don't support generating the stub IL
                    // in Ready-to-Run so we can correctly throw an exception at runtime when the user tries to
                    // use SetLastError=true when marshalling is disabled.
                    throw new NotSupportedException();
                }
                callsiteSetupCodeStream.Emit(ILOpcode.call, emitter.NewToken(
                                                 stubHelpersType.GetKnownMethod("ClearLastError", null)));
            }

            for (int i = 1; i < _marshallers.Length; i++)
            {
                nativeParameterTypes[i - 1] = _marshallers[i].NativeParameterType;
            }

            MethodSignature nativeSig = new MethodSignature(
                _targetMethod.Signature.Flags, 0, nativeReturnType,
                nativeParameterTypes);

            var rawTargetMethod = new PInvokeTargetNativeMethod(_targetMethod, nativeSig);

            callsiteSetupCodeStream.Emit(ILOpcode.call, emitter.NewToken(rawTargetMethod));

            // if the SetLastError flag is set in DllImport, call the PInvokeMarshal.SaveLastError
            // so that last error can be used later by calling Marshal.GetLastPInvokeError
            if (_importMetadata.Flags.SetLastError)
            {
                callsiteSetupCodeStream.Emit(ILOpcode.call, emitter.NewToken(
                                                 stubHelpersType.GetKnownMethod("SetLastError", null)));
            }
        }
        private void AddParameterMarshallingDependencies(ref DependencyList dependencies, NodeFactory factory, MethodDesc method, TypeDesc type)
        {
            if (type.IsDelegate)
            {
                dependencies.Add(factory.DelegateMarshallingData((DefType)type), "Delegate marshaling");
            }

            TypeSystemContext context = type.Context;

            if ((type.IsWellKnownType(WellKnownType.MulticastDelegate) ||
                 type == context.GetWellKnownType(WellKnownType.MulticastDelegate).BaseType))
            {
                // If we hit this p/invoke as part of delegate marshalling (i.e. this is a delegate
                // that has another delegate in the signature), blame the delegate type, not the marshalling thunk.
                // This should ideally warn from the use site (e.g. where GetDelegateForFunctionPointer
                // is called) but it's currently hard to get a warning from those spots and this guarantees
                // we won't miss a spot (e.g. a p/invoke that has a delegate and that delegate contains
                // a System.Delegate parameter).
                MethodDesc reportedMethod = method;
                if (reportedMethod is Internal.IL.Stubs.DelegateMarshallingMethodThunk delegateThunkMethod)
                {
                    reportedMethod = delegateThunkMethod.InvokeMethod;
                }

                _logger.LogWarning(reportedMethod, DiagnosticId.CorrectnessOfAbstractDelegatesCannotBeGuaranteed, DiagnosticUtilities.GetMethodSignatureDisplayName(method));
            }

            // struct may contain delegate fields, hence we need to add dependencies for it
            if (type.IsByRef)
            {
                type = ((ParameterizedType)type).ParameterType;
            }

            if (MarshalHelpers.IsStructMarshallingRequired(type))
            {
                foreach (FieldDesc field in type.GetFields())
                {
                    if (field.IsStatic)
                    {
                        continue;
                    }

                    AddParameterMarshallingDependencies(ref dependencies, factory, method, field.FieldType);
                }
            }
        }
Beispiel #13
0
        private void AddPInvokeParameterDependencies(ref DependencyList dependencies, NodeFactory factory, TypeDesc parameter)
        {
            if (parameter.IsDelegate)
            {
                dependencies.Add(factory.NecessaryTypeSymbol(parameter), "Delegate Marshalling Stub");

                dependencies.Add(factory.MethodEntrypoint(factory.InteropStubManager.GetOpenStaticDelegateMarshallingStub(parameter)), "Delegate Marshalling Stub");
                dependencies.Add(factory.MethodEntrypoint(factory.InteropStubManager.GetClosedDelegateMarshallingStub(parameter)), "Delegate Marshalling Stub");
            }
            else if (MarshalHelpers.IsStructMarshallingRequired(parameter))
            {
                dependencies.Add(factory.ConstructedTypeSymbol(factory.InteropStubManager.GetStructMarshallingType(parameter)), "Struct Marshalling Type");
                dependencies.Add(factory.MethodEntrypoint(factory.InteropStubManager.GetStructMarshallingManagedToNativeStub(parameter)), "Struct Marshalling stub");
                dependencies.Add(factory.MethodEntrypoint(factory.InteropStubManager.GetStructMarshallingNativeToManagedStub(parameter)), "Struct Marshalling stub");
                dependencies.Add(factory.MethodEntrypoint(factory.InteropStubManager.GetStructMarshallingCleanupStub(parameter)), "Struct Marshalling stub");
            }
        }
Beispiel #14
0
        public override IEnumerable <DependencyListEntry> GetStaticDependencies(NodeFactory factory)
        {
            InteropStateManager stateManager = ((CompilerGeneratedInteropStubManager)factory.InteropStubManager)._interopStateManager;

            yield return(new DependencyListEntry(factory.NecessaryTypeSymbol(_type), "Struct Marshalling Stub"));

            // Not all StructMarshalingDataNodes require marshalling - some are only present because we want to
            // generate field offset information for Marshal.OffsetOf.
            if (MarshalHelpers.IsStructMarshallingRequired(_type))
            {
                yield return(new DependencyListEntry(factory.MethodEntrypoint(stateManager.GetStructMarshallingManagedToNativeThunk(_type)), "Struct Marshalling stub"));

                yield return(new DependencyListEntry(factory.MethodEntrypoint(stateManager.GetStructMarshallingNativeToManagedThunk(_type)), "Struct Marshalling stub"));

                yield return(new DependencyListEntry(factory.MethodEntrypoint(stateManager.GetStructMarshallingCleanupThunk(_type)), "Struct Marshalling stub"));
            }
        }
Beispiel #15
0
 public static MethodIL EmitIL(MethodDesc method, PInvokeILEmitterConfiguration pinvokeILEmitterConfiguration, InteropStateManager interopStateManager)
 {
     try
     {
         return(new PInvokeILEmitter(method, pinvokeILEmitterConfiguration, interopStateManager).EmitIL());
     }
     catch (NotSupportedException)
     {
         string message = "Method '" + method.ToString() +
                          "' requires non-trivial marshalling that is not yet supported by this compiler.";
         return(MarshalHelpers.EmitExceptionBody(message, method));
     }
     catch (InvalidProgramException ex)
     {
         Debug.Assert(!String.IsNullOrEmpty(ex.Message));
         return(MarshalHelpers.EmitExceptionBody(ex.Message, method));
     }
 }
Beispiel #16
0
        private static void DescribeAttribute(IMFMediaType mediaType, int n, StringBuilder sb)
        {
            var variantPtr = Marshal.AllocHGlobal(MarshalHelpers.SizeOf <PropVariant>());

            try
            {
                Guid key;
                mediaType.GetItemByIndex(n, out key, variantPtr);
                var    val          = MarshalHelpers.PtrToStructure <PropVariant>(variantPtr);
                string propertyName = FieldDescriptionHelper.Describe(typeof(MediaFoundationAttributes), key);
                sb.AppendFormat("{0}={1}\r\n", propertyName, val.Value);
            }
            finally
            {
                PropVariant.Clear(variantPtr);
                Marshal.FreeHGlobal(variantPtr);
            }
        }
        public void OnNotify(IntPtr notifyData)
        {
            AudioVolumeNotificationDataStruct audioVolumeNotificationDataStruct = MarshalHelpers.PtrToStructure <AudioVolumeNotificationDataStruct>(notifyData);
            IntPtr value   = MarshalHelpers.OffsetOf <AudioVolumeNotificationDataStruct>("ChannelVolume");
            IntPtr pointer = (IntPtr)((long)notifyData + (long)value);

            float[] array = new float[audioVolumeNotificationDataStruct.nChannels];
            int     num   = 0;

            while ((long)num < (long)((ulong)audioVolumeNotificationDataStruct.nChannels))
            {
                array[num] = MarshalHelpers.PtrToStructure <float>(pointer);
                num++;
            }
            AudioVolumeNotificationData notificationData = new AudioVolumeNotificationData(audioVolumeNotificationDataStruct.guidEventContext, audioVolumeNotificationDataStruct.bMuted, audioVolumeNotificationDataStruct.fMasterVolume, array, audioVolumeNotificationDataStruct.guidEventContext);

            this.parent.FireNotification(notificationData);
        }
        private void AddDependenciesDueToPInvokeStruct(ref DependencyList dependencies, NodeFactory factory, TypeDesc type)
        {
            if (MarshalHelpers.IsStructMarshallingRequired(type))
            {
                dependencies.Add(factory.NecessaryTypeSymbol(type), "Struct Marshalling Stub");

                var stub = (StructMarshallingThunk)GetStructMarshallingManagedToNativeStub(type);
                dependencies.Add(factory.MethodEntrypoint(stub), "Struct Marshalling stub");
                dependencies.Add(factory.MethodEntrypoint(GetStructMarshallingNativeToManagedStub(type)), "Struct Marshalling stub");
                dependencies.Add(factory.MethodEntrypoint(GetStructMarshallingCleanupStub(type)), "Struct Marshalling stub");

                foreach (var inlineArrayCandidate in stub.GetInlineArrayCandidates())
                {
                    foreach (var method in inlineArrayCandidate.ElementType.GetMethods())
                    {
                        dependencies.Add(factory.MethodEntrypoint(method), "inline array marshalling stub");
                    }
                }
            }
        }
        /// <summary>
        /// Gets all the mixer controls
        /// </summary>
        /// <param name="mixerHandle">Mixer Handle</param>
        /// <param name="mixerLine">Mixer Line</param>
        /// <param name="mixerHandleType">Mixer Handle Type</param>
        /// <returns></returns>
        public static IList <MixerControl> GetMixerControls(IntPtr mixerHandle, MixerLine mixerLine,
                                                            MixerFlags mixerHandleType)
        {
            var controls = new List <MixerControl>();

            if (mixerLine.ControlsCount > 0)
            {
                int    mixerControlSize = MarshalHelpers.SizeOf <MixerInterop.MIXERCONTROL>();
                var    mlc = new MixerInterop.MIXERLINECONTROLS();
                IntPtr pmc = Marshal.AllocHGlobal(mixerControlSize * mixerLine.ControlsCount);
                mlc.cbStruct  = Marshal.SizeOf(mlc);
                mlc.dwLineID  = mixerLine.LineId;
                mlc.cControls = mixerLine.ControlsCount;
                mlc.pamxctrl  = pmc;
                mlc.cbmxctrl  = MarshalHelpers.SizeOf <MixerInterop.MIXERCONTROL>();
                try
                {
                    MmResult err = MixerInterop.mixerGetLineControls(mixerHandle, ref mlc, MixerFlags.All | mixerHandleType);
                    if (err != MmResult.NoError)
                    {
                        throw new MmException(err, "mixerGetLineControls");
                    }
                    for (int i = 0; i < mlc.cControls; i++)
                    {
                        Int64 address = pmc.ToInt64() + mixerControlSize * i;

                        var mc =
                            MarshalHelpers.PtrToStructure <MixerInterop.MIXERCONTROL>((IntPtr)address);
                        var mixerControl = GetMixerControl(mixerHandle, mixerLine.LineId, mc.dwControlID, mixerLine.Channels,
                                                           mixerHandleType);

                        controls.Add(mixerControl);
                    }
                }
                finally
                {
                    Marshal.FreeHGlobal(pmc);
                }
            }
            return(controls);
        }
Beispiel #20
0
        /// <summary>
        /// Helper function to retrieve a WaveFormat structure from a pointer
        /// </summary>
        /// <param name="pointer">WaveFormat structure</param>
        /// <returns></returns>
        public static WaveFormat MarshalFromPtr(IntPtr pointer)
        {
            var waveFormat = MarshalHelpers.PtrToStructure <WaveFormat>(pointer);

            switch (waveFormat.Encoding)
            {
            case WaveFormatEncoding.Pcm:
                // can't rely on extra size even being there for PCM so blank it to avoid reading
                // corrupt data
                waveFormat.extraSize = 0;
                break;

            default:
                if (waveFormat.ExtraSize > 0)
                {
                    waveFormat = MarshalHelpers.PtrToStructure <WaveFormatExtraData>(pointer);
                }
                break;
            }
            return(waveFormat);
        }
        public override void AddDependeciesDueToPInvoke(ref DependencyList dependencies, NodeFactory factory, MethodDesc method)
        {
            if (method.IsPInvoke && method.OwningType is MetadataType type && MarshalHelpers.IsRuntimeMarshallingEnabled(type.Module))
            {
                dependencies = dependencies ?? new DependencyList();

                MethodSignature methodSig = method.Signature;
                AddParameterMarshallingDependencies(ref dependencies, factory, method, methodSig.ReturnType);

                for (int i = 0; i < methodSig.Length; i++)
                {
                    AddParameterMarshallingDependencies(ref dependencies, factory, method, methodSig[i]);
                }
            }

            if (method.HasInstantiation)
            {
                dependencies = dependencies ?? new DependencyList();
                AddMarshalAPIsGenericDependencies(ref dependencies, factory, method);
            }
        }
Beispiel #22
0
        /// <summary>
        /// Determines if the specified output format is supported in shared mode
        /// </summary>
        /// <param name="shareMode">Share Mode</param>
        /// <param name="desiredFormat">Desired Format</param>
        /// <param name="closestMatchFormat">Output The closest match format.</param>
        /// <returns>True if the format is supported</returns>
        public bool IsFormatSupported(AudioClientShareMode shareMode, WaveFormat desiredFormat, out WaveFormatExtensible closestMatchFormat)
        {
            IntPtr pointerToPtr = GetPointerToPointer(); // IntPtr.Zero; // Marshal.AllocHGlobal(Marshal.SizeOf<WaveFormatExtensible>());

            closestMatchFormat = null;
            //int hresult = audioClientInterface.IsFormatSupported(shareMode, desiredFormat, pointerToPtr);
            var pDesiredFormat = desiredFormat.AsInterop();
            int hresult        = audioClientInterface.IsFormatSupported(shareMode, ref pDesiredFormat, pointerToPtr);

            var closestMatchPtr = MarshalHelpers.PtrToStructure <IntPtr>(pointerToPtr);

            if (closestMatchPtr != IntPtr.Zero)
            {
                //closestMatchFormat = MarshalHelpers.PtrToStructure<WaveFormatExtensible>(closestMatchPtr);
                closestMatchFormat = MarshalHelpers.PtrToStructure <WaveFormatExtensibleInterop>(closestMatchPtr);
                Marshal.FreeCoTaskMem(closestMatchPtr);
            }
            Marshal.FreeHGlobal(pointerToPtr);
            // S_OK is 0, S_FALSE = 1
            if (hresult == 0)
            {
                // directly supported
                return(true);
            }
            if (hresult == 1)
            {
                return(false);
            }
            if (hresult == (int)AudioClientErrors.UnsupportedFormat)
            {
                // Succeeded but the specified format is not supported in exclusive mode.
                return(shareMode != AudioClientShareMode.Exclusive);
            }
            Marshal.ThrowExceptionForHR(hresult);
            // shouldn't get here
            throw new NotSupportedException("Unknown hresult " + hresult);
        }
Beispiel #23
0
        public static WaveFormat MarshalFromPtr(IntPtr pointer)
        {
            WaveFormat         waveFormat = MarshalHelpers.PtrToStructure <WaveFormat>(pointer);
            WaveFormatEncoding encoding   = waveFormat.Encoding;

            if (encoding <= WaveFormatEncoding.Adpcm)
            {
                if (encoding == WaveFormatEncoding.Pcm)
                {
                    waveFormat.extraSize = 0;
                    return(waveFormat);
                }
                if (encoding == WaveFormatEncoding.Adpcm)
                {
                    waveFormat = MarshalHelpers.PtrToStructure <AdpcmWaveFormat>(pointer);
                    return(waveFormat);
                }
            }
            else
            {
                if (encoding == WaveFormatEncoding.Gsm610)
                {
                    waveFormat = MarshalHelpers.PtrToStructure <Gsm610WaveFormat>(pointer);
                    return(waveFormat);
                }
                if (encoding == WaveFormatEncoding.Extensible)
                {
                    waveFormat = MarshalHelpers.PtrToStructure <WaveFormatExtensible>(pointer);
                    return(waveFormat);
                }
            }
            if (waveFormat.ExtraSize > 0)
            {
                waveFormat = MarshalHelpers.PtrToStructure <WaveFormatExtraData>(pointer);
            }
            return(waveFormat);
        }
        /// <summary>
        /// Determines if the specified output format is supported in shared mode
        /// </summary>
        /// <param name="shareMode">Share Mode</param>
        /// <param name="desiredFormat">Desired Format</param>
        /// <param name="closestMatchFormat">Output The closest match format.</param>
        /// <returns>True if the format is supported</returns>
        public bool IsFormatSupported(AudioClientShareMode shareMode, WaveFormat desiredFormat, out WaveFormatExtensible closestMatchFormat)
        {
            IntPtr pointerToPtr = GetPointerToPointer(); // IntPtr.Zero; // Marshal.AllocHGlobal(Marshal.SizeOf<WaveFormatExtensible>());

            closestMatchFormat = null;
            int hresult = audioClientInterface.IsFormatSupported(shareMode, desiredFormat, pointerToPtr);

            var closestMatchPtr = MarshalHelpers.PtrToStructure <IntPtr>(pointerToPtr);

            if (closestMatchPtr != IntPtr.Zero)
            {
                closestMatchFormat = MarshalHelpers.PtrToStructure <WaveFormatExtensible>(closestMatchPtr);
                Marshal.FreeCoTaskMem(closestMatchPtr);
            }
            Marshal.FreeHGlobal(pointerToPtr);
            // S_OK is 0, S_FALSE = 1
            if (hresult == 0)
            {
                // directly supported
                return(true);
            }
            if (hresult == 1)
            {
                return(false);
            }
            if (hresult == (int)AudioClientErrors.UnsupportedFormat)
            {
                // documentation is confusing as to what this flag means
                // https://docs.microsoft.com/en-us/windows/desktop/api/audioclient/nf-audioclient-iaudioclient-isformatsupported
                // "Succeeded but the specified format is not supported in exclusive mode."
                return(false); // shareMode != AudioClientShareMode.Exclusive;
            }
            Marshal.ThrowExceptionForHR(hresult);
            // shouldn't get here
            throw new NotSupportedException("Unknown hresult " + hresult);
        }
Beispiel #25
0
        private bool IsStubRequired()
        {
            MethodDesc method = _methodData.TargetMethod;

            Debug.Assert(method.IsPInvoke);

            if (MarshalHelpers.UseLazyResolution(method, _methodData.ImportMetadata.Module, _methodData.PInvokeILEmitterConfiguration))
            {
                return(true);
            }
            if ((_methodData.ImportMetadata.Attributes & PInvokeAttributes.SetLastError) == PInvokeAttributes.SetLastError)
            {
                return(true);
            }

            for (int i = 0; i < _marshallers.Length; i++)
            {
                if (_marshallers[i].IsMarshallingRequired())
                {
                    return(true);
                }
            }
            return(false);
        }
Beispiel #26
0
        private void EmitPInvokeCall(PInvokeILCodeStreams ilCodeStreams)
        {
            ILEmitter         emitter                 = ilCodeStreams.Emitter;
            ILCodeStream      fnptrLoadStream         = ilCodeStreams.FunctionPointerLoadStream;
            ILCodeStream      callsiteSetupCodeStream = ilCodeStreams.CallsiteSetupCodeStream;
            TypeSystemContext context                 = _targetMethod.Context;

            TypeDesc nativeReturnType = _marshallers[0].NativeParameterType;

            TypeDesc[] nativeParameterTypes = new TypeDesc[_marshallers.Length - 1];

            // if the SetLastError flag is set in DllImport, clear the error code before doing P/Invoke
            if (_flags.SetLastError)
            {
                callsiteSetupCodeStream.Emit(ILOpcode.call, emitter.NewToken(
                                                 InteropTypes.GetPInvokeMarshal(context).GetKnownMethod("ClearLastWin32Error", null)));
            }

            for (int i = 1; i < _marshallers.Length; i++)
            {
                nativeParameterTypes[i - 1] = _marshallers[i].NativeParameterType;
            }

            if (MarshalHelpers.UseLazyResolution(_targetMethod,
                                                 _importMetadata.Module,
                                                 _pInvokeILEmitterConfiguration))
            {
                MetadataType lazyHelperType   = context.GetHelperType("InteropHelpers");
                FieldDesc    lazyDispatchCell = _interopStateManager.GetPInvokeLazyFixupField(_targetMethod);

                fnptrLoadStream.Emit(ILOpcode.ldsflda, emitter.NewToken(lazyDispatchCell));
                fnptrLoadStream.Emit(ILOpcode.call, emitter.NewToken(lazyHelperType
                                                                     .GetKnownMethod("ResolvePInvoke", null)));

                MethodSignatureFlags unmanagedCallConv = _flags.UnmanagedCallingConvention;

                MethodSignature nativeSig = new MethodSignature(
                    _targetMethod.Signature.Flags | unmanagedCallConv, 0, nativeReturnType,
                    nativeParameterTypes);

                ILLocalVariable vNativeFunctionPointer = emitter.NewLocal(context
                                                                          .GetWellKnownType(WellKnownType.IntPtr));

                fnptrLoadStream.EmitStLoc(vNativeFunctionPointer);
                callsiteSetupCodeStream.EmitLdLoc(vNativeFunctionPointer);
                callsiteSetupCodeStream.Emit(ILOpcode.calli, emitter.NewToken(nativeSig));
            }
            else
            {
                // Eager call
                MethodSignature nativeSig = new MethodSignature(
                    _targetMethod.Signature.Flags, 0, nativeReturnType, nativeParameterTypes);

                MethodDesc nativeMethod =
                    new PInvokeTargetNativeMethod(_targetMethod, nativeSig);

                callsiteSetupCodeStream.Emit(ILOpcode.call, emitter.NewToken(nativeMethod));
            }

            // if the SetLastError flag is set in DllImport, call the PInvokeMarshal.
            // SaveLastWin32Error so that last error can be used later by calling
            // PInvokeMarshal.GetLastWin32Error
            if (_flags.SetLastError)
            {
                callsiteSetupCodeStream.Emit(ILOpcode.call, emitter.NewToken(
                                                 InteropTypes.GetPInvokeMarshal(context)
                                                 .GetKnownMethod("SaveLastWin32Error", null)));
            }
        }
Beispiel #27
0
 public static IEnumerable <SyncUserHandle> GetAllLoggedInUsers()
 {
     return(MarshalHelpers.GetCollection <IntPtr>(NativeMethods.get_logged_in_users, bufferSize: 8)
            .Select(h => new SyncUserHandle(h)));
 }
Beispiel #28
0
        private MethodIL EmitIL()
        {
            PInvokeILCodeStreams pInvokeILCodeStreams = new PInvokeILCodeStreams();
            ILEmitter            emitter                 = pInvokeILCodeStreams.Emitter;
            ILCodeStream         fnptrLoadStream         = pInvokeILCodeStreams.FunctionPointerLoadStream;
            ILCodeStream         callsiteSetupCodeStream = pInvokeILCodeStreams.CallsiteSetupCodeStream;
            ILCodeStream         unmarshallingCodestream = pInvokeILCodeStreams.UnmarshallingCodestream;
            TypeSystemContext    context                 = _targetMethod.Context;

            // Marshal the arguments
            for (int i = 0; i < _marshallers.Length; i++)
            {
                _marshallers[i].EmitMarshallingIL(pInvokeILCodeStreams);
            }


            // if the SetLastError flag is set in DllImport, clear the error code before doing P/Invoke
            if (_importMetadata.Flags.SetLastError)
            {
                callsiteSetupCodeStream.Emit(ILOpcode.call, emitter.NewToken(
                                                 InteropTypes.GetPInvokeMarshal(context).GetKnownMethod("ClearLastWin32Error", null)));
            }

            // make the call

            DelegateMarshallingMethodThunk delegateMethod = _targetMethod as DelegateMarshallingMethodThunk;

            if (delegateMethod != null)
            {
                EmitDelegateCall(delegateMethod, pInvokeILCodeStreams);
            }
            else
            {
                TypeDesc   nativeReturnType     = _marshallers[0].NativeParameterType;
                TypeDesc[] nativeParameterTypes = new TypeDesc[_marshallers.Length - 1];

                for (int i = 1; i < _marshallers.Length; i++)
                {
                    nativeParameterTypes[i - 1] = _marshallers[i].NativeParameterType;
                }

                if (MarshalHelpers.UseLazyResolution(_targetMethod,
                                                     _importMetadata.Module,
                                                     _pInvokeILEmitterConfiguration))
                {
                    MetadataType lazyHelperType   = _targetMethod.Context.GetHelperType("InteropHelpers");
                    FieldDesc    lazyDispatchCell = new PInvokeLazyFixupField(_targetMethod);

                    fnptrLoadStream.Emit(ILOpcode.ldsflda, emitter.NewToken(lazyDispatchCell));
                    fnptrLoadStream.Emit(ILOpcode.call, emitter.NewToken(lazyHelperType
                                                                         .GetKnownMethod("ResolvePInvoke", null)));

                    MethodSignatureFlags unmanagedCallConv = _importMetadata.Flags.UnmanagedCallingConvention;

                    MethodSignature nativeSig = new MethodSignature(
                        _targetMethod.Signature.Flags | unmanagedCallConv, 0, nativeReturnType,
                        nativeParameterTypes);

                    ILLocalVariable vNativeFunctionPointer = emitter.NewLocal(_targetMethod.Context
                                                                              .GetWellKnownType(WellKnownType.IntPtr));

                    fnptrLoadStream.EmitStLoc(vNativeFunctionPointer);
                    callsiteSetupCodeStream.EmitLdLoc(vNativeFunctionPointer);
                    callsiteSetupCodeStream.Emit(ILOpcode.calli, emitter.NewToken(nativeSig));
                }
                else
                {
                    // Eager call
                    MethodSignature nativeSig = new MethodSignature(
                        _targetMethod.Signature.Flags, 0, nativeReturnType, nativeParameterTypes);

                    MethodDesc nativeMethod =
                        new PInvokeTargetNativeMethod(_targetMethod, nativeSig);

                    callsiteSetupCodeStream.Emit(ILOpcode.call, emitter.NewToken(nativeMethod));
                }
            }

            // if the SetLastError flag is set in DllImport, call the PInvokeMarshal.
            // SaveLastWin32Error so that last error can be used later by calling
            // PInvokeMarshal.GetLastWin32Error
            if (_importMetadata.Flags.SetLastError)
            {
                callsiteSetupCodeStream.Emit(ILOpcode.call, emitter.NewToken(
                                                 InteropTypes.GetPInvokeMarshal(context)
                                                 .GetKnownMethod("SaveLastWin32Error", null)));
            }

            unmarshallingCodestream.Emit(ILOpcode.ret);

            return(new  PInvokeILStubMethodIL((ILStubMethodIL)emitter.Link(_targetMethod),
                                              IsStubRequired()));
        }
Beispiel #29
0
 private IntPtr GetPointerToPointer()
 {
     return(Marshal.AllocHGlobal(MarshalHelpers.SizeOf <IntPtr>()));
 }
Beispiel #30
0
 public IEnumerable <SyncUserHandle> GetAllLoggedInUsers()
 {
     return(MarshalHelpers.GetCollection((IntPtr[] buf, IntPtr len, out NativeException ex) => NativeMethods.get_logged_in_users(this, buf, len, out ex), bufferSize: 8)
            .Select(h => new SyncUserHandle(h)));
 }