コード例 #1
0
ファイル: CfxBinaryValue.cs プロジェクト: xmcy0011/NanUI
 /// <summary>
 /// Creates a new object that is not owned by any other object. The specified
 /// |data| will be copied.
 /// </summary>
 public static CfxBinaryValue Create(byte[] data)
 {
     if(data == null || data.Length == 0) {
         throw new ArgumentException("Data is null or zero length", "data");
     }
     var po = new PinnedObject(data);
     var retval = CfxBinaryValue.Create(po.PinnedPtr, data.Length);
     po.Free();
     return retval;
 }
コード例 #2
0
ファイル: CfxZipReader.cs プロジェクト: xmcy0011/NanUI
 /// <summary>
 /// Read uncompressed file contents into the specified buffer. Returns 
 /// 0 if at the end of file, or the number of bytes read.
 /// Throws an exception if an error occurred.
 /// </summary>
 public int ReadFile(byte[] buffer)
 {
     if(buffer == null || buffer.Length == 0)
         throw new ArgumentException("Buffer can't be null or zero length.", "buffer");
     var pb = new PinnedObject(buffer);
     var retval = CfxApi.cfx_zip_reader_read_file(NativePtr, pb.PinnedPtr, buffer.Length);
     pb.Free();
     if(retval < 0)
         throw new CfxException("Failed to read from zip file");
     return retval;
 }
コード例 #3
0
ファイル: CfxBinaryValue.cs プロジェクト: xmcy0011/NanUI
        /// <summary>
        /// Read up to (buffer.Length - bufferOffset) bytes into |buffer|. Reading begins at
        /// the specified byte dataOffset. Writing begins at the
        /// specified byte bufferOffset.
        /// Returns the number of bytes read.
        /// </summary>
        public int GetData(byte[] buffer, int bufferOffset, int dataOffset)
        {
            if(buffer == null || buffer.Length == 0) {
                throw new ArgumentException("Buffer is null or zero length.", "buffer");
            }

            var maxBytes = buffer.Length - bufferOffset;
            if(maxBytes <= 0)
                throw new ArgumentException("bufferOffset >= buffer.Length.", "bufferOffset");

            var po = new PinnedObject(buffer);

            var retval = CfxApi.cfx_binary_value_get_data(NativePtr, po.PinnedPtr + bufferOffset, maxBytes, dataOffset);
            po.Free();
            return retval;
        }
コード例 #4
0
        /// <summary>Writes the specified structure value of type <typeparamref name="T"/> into a binary stream.</summary>
        /// <typeparam name="T">The type of the structure value to write.</typeparam>
        /// <param name="writer">The <see cref="BinaryWriter"/> instance to write into.</param>
        /// <param name="value">The value to write.</param>
        public static void Write <T>(this BinaryWriter writer, T value)
        {
            if (value == null)
            {
                return;
            }
            if (!typeof(T).IsBlittable())
            {
                throw new ArgumentException(@"The type parameter layout is not sequential or explicit.", nameof(T));
            }
            var sz    = Marshal.SizeOf(value);
            var bytes = new byte[sz];

            using (var ptr = new PinnedObject(value))
                Marshal.Copy(ptr, bytes, 0, sz);
            writer.Write(bytes);
        }
        private void GetMetadata(Stream stream, long length, out ModuleMetadata metadata, out object lifeTimeObject)
        {
            if (stream is ISupportDirectMemoryAccess directAccess)
            {
                metadata       = ModuleMetadata.CreateFromMetadata(directAccess.GetPointer(), (int)length);
                lifeTimeObject = stream;
                return;
            }

            PinnedObject pinnedObject;

            if (stream is MemoryStream memory &&
                memory.TryGetBuffer(out var buffer) &&
                buffer.Offset == 0)
            {
                pinnedObject = new PinnedObject(buffer.Array, buffer.Count);
            }
コード例 #6
0
ファイル: Gui.cs プロジェクト: tottaka/SharpPi
        /// <summary>
        /// Sets per-frame data based on the associated window.
        /// This is called by Update(float).
        /// </summary>
        private void SetPerFrameImGuiData()
        {
            ImGuiIOPtr io = ImGui.GetIO();

            io.DisplaySize             = new System.Numerics.Vector2(_windowWidth / _scaleFactor.X, _windowHeight / _scaleFactor.Y);
            io.DisplayFramebufferScale = _scaleFactor;
            io.DeltaTime = Time.deltaTime == 0.0f ? (1f / 60f) : Time.deltaTime; // DeltaTime is in seconds.

            if (FontCreationQueue.Count > 0)
            {
                foreach (Tuple <string, byte[], float> font in FontCreationQueue)
                {
                    using (PinnedObject <byte[]> fontObject = new PinnedObject <byte[]>(font.Item2))
                        Fonts.Add(font.Item1, io.Fonts.AddFontFromMemoryTTF(fontObject.Address, font.Item2.Length, font.Item3));
                }

                FontCreationQueue.Clear();
                RecreateFontDeviceTexture();
            }
        }
コード例 #7
0
        static void Main(string[] args)
        {
            Console.WriteLine($"sizeof(int): {sizeof(int)}");
            Console.WriteLine($"sizeof(long): {sizeof(long)}");
            Console.WriteLine($"{FakeADWrapper.ErrorToString(Error.Success)}");

#if I_FAILED
            int cursor                   = 0;
            var pinnedCursor             = new PinnedObject(cursor);
            var pinnedCursorOpaqueHandle = pinnedCursor.ToIntPtr();
#endif
            var fakeAd = new FakeADWrapper(
                bytesPerSecond: CharsPerSecond,
                timeSliceInMilliseconds: 100,
                timeoutSliceCount: 3,
                port: 7373,
                callback: Typer.TypeIn,
#if I_FAILED
#if false
                context: pinnedCursor);
#elif false
                context : pinnedCursor.ToIntPtr());
#else
                context : pinnedCursorOpaqueHandle);
#endif
#else
                context : IntPtr.Zero);
#endif

            var buffer = new UnmanagedBuffer(sizeof(byte));
            while (fakeAd.Read(buffer, sizeof(byte)) == sizeof(byte))
            {
                Console.Write((char)buffer.Read <byte>());
            }

#if I_FAILED
            Console.WriteLine($"Cursor: {cursor}");
#endif

            Console.ReadKey();
        }
コード例 #8
0
ファイル: CldApiTests.cs プロジェクト: zhuxb711/Vanara
                    static void ShowInfo <T>(object s, CloudSyncCallbackArgs <T> e) where T: struct
                    {
                        Debug.WriteLine($"\n{typeof(T).Name}: {e.NormalizedPath ?? "(null)"}, {e.FileSize}\n" +
                                        Newtonsoft.Json.JsonConvert.SerializeObject(e.ParamData, Newtonsoft.Json.Formatting.Indented, new Newtonsoft.Json.Converters.StringEnumConverter()));

                        if (typeof(T) == typeof(CF_CALLBACK_PARAMETERS.RENAME))
                        {
                            e.OperationType = CF_OPERATION_TYPE.CF_OPERATION_TYPE_ACK_RENAME;
                            e.OpParam       = CF_OPERATION_PARAMETERS.Create(new CF_OPERATION_PARAMETERS.ACKRENAME());
                        }
                        else if (typeof(T) == typeof(CF_CALLBACK_PARAMETERS.DEHYDRATE))
                        {
                            e.OperationType = CF_OPERATION_TYPE.CF_OPERATION_TYPE_ACK_DEHYDRATE;
                            e.OpParam       = CF_OPERATION_PARAMETERS.Create(new CF_OPERATION_PARAMETERS.ACKDEHYDRATE());
                        }
                        else if (typeof(T) == typeof(CF_CALLBACK_PARAMETERS.DELETE))
                        {
                            e.OperationType = CF_OPERATION_TYPE.CF_OPERATION_TYPE_ACK_DELETE;
                            e.OpParam       = CF_OPERATION_PARAMETERS.Create(new CF_OPERATION_PARAMETERS.ACKDELETE());
                        }
                        else if (typeof(T) == typeof(CF_CALLBACK_PARAMETERS.FETCHDATA))
                        {
                            var opInfo    = e.MakeOpInfo(CF_OPERATION_TYPE.CF_OPERATION_TYPE_TRANSFER_DATA);
                            using var buf = new PinnedObject(File.ReadAllBytes(TestCaseSources.BmpFile));
                            var opParam   = CF_OPERATION_PARAMETERS.Create(new CF_OPERATION_PARAMETERS.TRANSFERDATA {
                                Buffer = buf, Length = new FileInfo(TestCaseSources.BmpFile).Length
                            });
                            var hr = CfExecute(opInfo, ref opParam);
                            if (hr.Failed)
                            {
                                Debug.WriteLine("CfExecute for transfer failed: " + hr.FormatMessage());
                            }
                            hr = CfReportProviderProgress(e.ConnectionKey, e.TransferKey, 100, 100);
                            if (hr.Failed)
                            {
                                Debug.WriteLine("CfReportProviderProgress for transfer failed: " + hr.FormatMessage());
                            }
                        }
                    }
コード例 #9
0
        public DataLib.CartData GetSingleProfile()
        {
            try
            {
                var data = new DataLib.CartData();
                if (_connected)
                {
                    _sendCommand = SendCommand.GetProfileAdvance;
                    _deviceData.ProfileData.Clear();
                    _deviceData.MeasureData.Clear();
                    _measureDatas.Clear();
                    LJSetting.SetOpMode(_currentDeviceId, LJV7IF_OP_MODE.ADVANCED);
                    Thread.Sleep(50);
                    // Set the command function
                    LJV7IF_PROFILE_INFO profileInfo = new LJV7IF_PROFILE_INFO();
                    uint  dataSize    = GetOneProfileDataSize();
                    int[] profileData = new int[dataSize / Marshal.SizeOf(typeof(int))];
                    LJV7IF_MEASURE_DATA[] measureData = new LJV7IF_MEASURE_DATA[NativeMethods.MeasurementDataCount];

                    using (PinnedObject pin = new PinnedObject(profileData))
                    {
                        // Send the command
                        rc = (Rc)NativeMethods.LJV7IF_GetProfileAdvance(_currentDeviceId, ref profileInfo, pin.Pointer, dataSize, measureData);
                        CheckReturnValue(rc);

                        // Response data display
                        _measureDatas.Add(new MeasureData(0, measureData));
                        ExtractProfileData(1, ref profileInfo, profileData);
                    }
                }
                return(_deviceData.ProfileData[0].GetCartData(_scalingMultiplier));
            }
            catch (Exception)
            {
                throw;
            }
        }
コード例 #10
0
ファイル: UDT.cs プロジェクト: Danmer/uberdemotools
        public static bool CreateFlagCapturePatternInfo(ref udtPatternInfo pattern, ArgumentResources resources, udtCutByFlagCaptureArg rules)
        {
            var pinnedRules = new PinnedObject(rules);
            resources.PinnedObjects.Add(pinnedRules);

            pattern.Type = (UInt32)udtPatternType.FlagCaptures;
            pattern.TypeSpecificInfo = pinnedRules.Address;

            return true;
        }
コード例 #11
0
ファイル: UDT.cs プロジェクト: Danmer/uberdemotools
        public static bool CreateChatPatternInfo(ref udtPatternInfo pattern, ArgumentResources resources, List<ChatRule> rules)
        {
            if(rules.Count == 0)
            {
                return false;
            }

            var rulesArray = new UDT_DLL.udtCutByChatRule[rules.Count];
            for(var i = 0; i < rules.Count; ++i)
            {
                rulesArray[i].CaseSensitive = (UInt32)(rules[i].CaseSensitive ? 1 : 0);
                rulesArray[i].ChatOperator = GetOperatorFromString(rules[i].Operator);
                rulesArray[i].IgnoreColorCodes = (UInt32)(rules[i].IgnoreColors ? 1 : 0);
                rulesArray[i].Pattern = Marshal.StringToHGlobalAnsi(rules[i].Value);
                resources.GlobalAllocationHandles.Add(rulesArray[i].Pattern);
            }
            var pinnedRulesArray = new PinnedObject(rulesArray);

            var cutByChatArg = new udtCutByChatArg();
            cutByChatArg.Rules = pinnedRulesArray.Address;
            cutByChatArg.RuleCount = (UInt32)rulesArray.Length;
            var pinnedRules = new PinnedObject(cutByChatArg);

            resources.PinnedObjects.Add(pinnedRulesArray);
            resources.PinnedObjects.Add(pinnedRules);

            pattern.Type = (UInt32)udtPatternType.GlobalChat;
            pattern.TypeSpecificInfo = pinnedRules.Address;

            return true;
        }
コード例 #12
0
ファイル: PinnedString.cs プロジェクト: xmcy0011/NanUI
 public PinnedString(string s)
 {
     Obj = new PinnedObject(s);
     Length = s != null ? s.Length : 0;
 }
コード例 #13
0
        public static bool WriteVariableStringAttribute(hid_t hid, string key, IEnumerable <string> values, bool utf8)
        {
            if (key == null)
            {
                throw new ArgumentNullException("key");
            }

            if (values == null)
            {
                throw new ArgumentNullException("values");
            }

            var exists = H5A.exists(hid, key);

            if (exists < 0)
            {
                throw new Exception("H5A.exists failed");
            }

            if (exists == 0) // Attribute doesn't exist
            {
#if true
                var type = H5T.create(H5T.class_t.STRING, H5T.VARIABLE);
                if (type < 0)
                {
                    throw new Exception("Failed to create string type");
                }
#else
                var type = H5T.copy(H5T.C_S1);
                if (type < 0)
                {
                    throw new Exception("Failed to create string type");
                }

                if (H5T.set_size(type, H5T.VARIABLE) < 0)
                {
                    H5T.close(type);
                    throw new Exception("Failed to set type size");
                }
#endif

                if (utf8)
                {
                    if (H5T.set_cset(type, H5T.cset_t.UTF8) < 0)
                    {
                        H5T.close(type);
                        throw new Exception("Failed to set cset");
                    }
                }

                if (H5T.set_strpad(type, H5T.str_t.NULLTERM) < 0)
                {
                    H5T.close(type);
                    throw new Exception("Failed to set strpad");
                }

                var space = values.Count() == 1 ? H5S.create(H5S.class_t.SCALAR)
                    : H5S.create_simple(1, new ulong[1] {
                    (ulong)values.Count()
                }, null);
                if (space < 0)
                {
                    H5T.close(type);
                    throw new Exception("Failed to create data space");
                }

                var attribute = H5A.create(hid, key, type, space);
                H5S.close(space);
                if (attribute < 0)
                {
                    H5T.close(type);
                    throw new Exception(string.Format("Failed to create attribute \"{0}\"", key));
                }

                var pinnedObjects = new PinnedObject[values.Count()];
                var data          = new IntPtr[values.Count()];
                int count         = 0;
                foreach (string str in values)
                {
                    var bytes = str.ToBytes(utf8);
                    pinnedObjects[count] = new PinnedObject(bytes);
                    data[count]          = pinnedObjects[count];
                    count += 1;
                }

                H5A.write(attribute, type, new PinnedObject(data));

                H5T.close(type);
                H5A.close(attribute);
            }
            else
            {
                // Attribute exists.
                var attribute = H5A.open(hid, key);
                if (attribute < 0)
                {
                    throw new Exception(string.Format("Failed to open attribute \"{0}\"", key));
                }

                var type = H5A.get_type(attribute);
                if (type < 0)
                {
                    H5A.close(attribute);
                    throw new Exception("Failed to get data type");
                }

                var pinnedObjects = new PinnedObject[values.Count()];
                var data          = new IntPtr[values.Count()];
                int count         = 0;
                foreach (string str in values)
                {
                    var bytes = str.ToBytes(utf8);
                    pinnedObjects[count] = new PinnedObject(bytes);
                    data[count]          = pinnedObjects[count];
                    count += 1;
                }

                H5A.write(attribute, type, new PinnedObject(data));

                H5T.close(type);
                H5A.close(attribute);
            }

            return(true);
        }
コード例 #14
0
ファイル: HDF5Helper.cs プロジェクト: Tomance/Ongoing-Study
        private static bool CreateOrOverwriteVariableStringAttribute(hid_t hid, string key, IEnumerable <string> values, bool utf8)
        {
            if (H5A.exists(hid, key) == 0)
            {
                // Attribute doesn't exist.
#if true
                var type = H5T.create(H5T.class_t.STRING, H5T.VARIABLE);
                if (type < 0)
                {
                    return(false);
                }
#else
                var type = H5T.copy(H5T.C_S1);
                if (type < 0)
                {
                    return(false);
                }

                H5T.set_size(type, H5T.VARIABLE);
#endif

                if (utf8)
                {
                    H5T.set_cset(type, H5T.cset_t.UTF8);
                }
                H5T.set_strpad(type, H5T.str_t.NULLTERM);

                var space = values.Count() == 1 ? H5S.create(H5S.class_t.SCALAR)
                    : H5S.create_simple(1, new ulong[1] {
                    (ulong)values.Count()
                }, null);
                if (space < 0)
                {
                    H5T.close(type);
                    return(false);
                }

                var attribute = H5A.create(hid, key, type, space);
                if (attribute < 0)
                {
                    H5S.close(space);
                    H5T.close(type);
                    return(false);
                }

                H5S.close(space);

                var pinnedObjects = new PinnedObject[values.Count()];
                var data          = new IntPtr[values.Count()];
                int count         = 0;
                foreach (string str in values)
                {
                    var bytes = str.ToBytes(utf8);
                    pinnedObjects[count] = new PinnedObject(bytes);
                    data[count]          = pinnedObjects[count];
                    count += 1;
                }

                H5A.write(attribute, type, new PinnedObject(data));

                H5T.close(type);
                H5A.close(attribute);
            }
            else
            {
                // Attribute exists.
                var attribute = H5A.open(hid, key);
                if (attribute < 0)
                {
                    return(false);
                }

                var type = H5A.get_type(attribute);
                if (type < 0)
                {
                    H5A.close(attribute);
                    return(false);
                }

                var pinnedObjects = new PinnedObject[values.Count()];
                var data          = new IntPtr[values.Count()];
                int count         = 0;
                foreach (string str in values)
                {
                    var bytes = str.ToBytes(utf8);
                    pinnedObjects[count] = new PinnedObject(bytes);
                    data[count]          = pinnedObjects[count];
                    count += 1;
                }

                H5A.write(attribute, type, new PinnedObject(data));

                H5T.close(type);
                H5A.close(attribute);
            }

            return(true);
        }
コード例 #15
0
ファイル: UDT.cs プロジェクト: Danmer/uberdemotools
        private static List<DemoInfo> ParseDemosImpl(ref udtParseArg parseArg, List<string> filePaths, int maxThreadCount, int inputIndexBase)
        {
            var errorCodeArray = new Int32[filePaths.Count];
            var filePathArray = new IntPtr[filePaths.Count];
            for(var i = 0; i < filePaths.Count; ++i)
            {
                filePathArray[i] = Marshal.StringToHGlobalAnsi(Path.GetFullPath(filePaths[i]));
            }

            var pinnedPlugIns = new PinnedObject(PlugInArray);
            parseArg.PlugInCount = (UInt32)PlugInArray.Length;
            parseArg.PlugIns = pinnedPlugIns.Address;

            var pinnedFilePaths = new PinnedObject(filePathArray);
            var pinnedErrorCodes = new PinnedObject(errorCodeArray);
            var multiParseArg = new udtMultiParseArg();
            multiParseArg.FileCount = (UInt32)filePathArray.Length;
            multiParseArg.FilePaths = pinnedFilePaths.Address;
            multiParseArg.OutputErrorCodes = pinnedErrorCodes.Address;
            multiParseArg.MaxThreadCount = (UInt32)maxThreadCount;

            udtParserContextGroupRef contextGroup = IntPtr.Zero;
            var result = udtParseDemoFiles(ref contextGroup, ref parseArg, ref multiParseArg);
            pinnedPlugIns.Free();
            pinnedFilePaths.Free();
            pinnedErrorCodes.Free();
            for(var i = 0; i < filePathArray.Length; ++i)
            {
                Marshal.FreeHGlobal(filePathArray[i]);
            }

            if(result != udtErrorCode.None && result != udtErrorCode.OperationCanceled)
            {
                udtDestroyContextGroup(contextGroup);
                App.GlobalLogError("Failed to parse demos: " + GetErrorCodeString(result));
                return null;
            }

            uint contextCount = 0;
            if(udtGetContextCountFromGroup(contextGroup, ref contextCount) != udtErrorCode.None)
            {
                udtDestroyContextGroup(contextGroup);
                return null;
            }

            var infoList = new List<DemoInfo>();
            for(uint i = 0; i < contextCount; ++i)
            {
                udtParserContextRef context = IntPtr.Zero;
                if(udtGetContextFromGroup(contextGroup, i, ref context) != udtErrorCode.None)
                {
                    udtDestroyContextGroup(contextGroup);
                    return null;
                }

                uint demoCount = 0;
                if(udtGetDemoCountFromContext(context, ref demoCount) != udtErrorCode.None)
                {
                    udtDestroyContextGroup(contextGroup);
                    return null;
                }

                for(uint j = 0; j < demoCount; ++j)
                {
                    uint inputIdx = 0;
                    if(udtGetDemoInputIndex(context, j, ref inputIdx) != udtErrorCode.None)
                    {
                        continue;
                    }

                    var errorCode = errorCodeArray[(int)inputIdx];
                    if(errorCode != (Int32)udtErrorCode.None)
                    {
                        if(errorCode != (Int32)udtErrorCode.Unprocessed && errorCode != (Int32)udtErrorCode.OperationCanceled)
                        {
                            var fileName = Path.GetFileName(filePaths[(int)inputIdx]);
                            var errorCodeString = GetErrorCodeString((udtErrorCode)errorCode);
                            App.GlobalLogError("Failed to parse demo file {0}: {1}", fileName, errorCodeString);
                        }
                        continue;
                    }

                    var filePath = filePaths[(int)inputIdx];
                    var protocol = udtGetProtocolByFilePath(filePath);
                    var info = new DemoInfo();
                    info.Analyzed = true;
                    info.InputIndex = inputIndexBase + (int)inputIdx;
                    info.FilePath = Path.GetFullPath(filePath);
                    info.Protocol = UDT_DLL.GetProtocolAsString(protocol);

                    ExtractDemoInfo(context, j, ref info);
                    infoList.Add(info);
                }
            }

            udtDestroyContextGroup(contextGroup);

            // Keep the original input order.
            infoList.Sort((a, b) => a.InputIndex - b.InputIndex);

            return infoList;
        }
コード例 #16
0
ファイル: UDT.cs プロジェクト: Danmer/uberdemotools
        private static bool ConvertDemosImpl(ref udtParseArg parseArg, udtProtocol outProtocol, List<MapConversionRule> mapRules, List<string> filePaths, int maxThreadCount)
        {
            var resources = new ArgumentResources();
            var errorCodeArray = new Int32[filePaths.Count];
            var filePathArray = new IntPtr[filePaths.Count];
            for(var i = 0; i < filePaths.Count; ++i)
            {
                var filePath = Marshal.StringToHGlobalAnsi(Path.GetFullPath(filePaths[i]));
                filePathArray[i] = filePath;
                resources.GlobalAllocationHandles.Add(filePath);
            }

            var pinnedFilePaths = new PinnedObject(filePathArray);
            var pinnedErrorCodes = new PinnedObject(errorCodeArray);
            resources.PinnedObjects.Add(pinnedFilePaths);
            resources.PinnedObjects.Add(pinnedErrorCodes);
            var multiParseArg = new udtMultiParseArg();
            multiParseArg.FileCount = (UInt32)filePathArray.Length;
            multiParseArg.FilePaths = pinnedFilePaths.Address;
            multiParseArg.OutputErrorCodes = pinnedErrorCodes.Address;
            multiParseArg.MaxThreadCount = (UInt32)maxThreadCount;

            var conversionArg = new udtProtocolConversionArg();
            conversionArg.OutputProtocol = (UInt32)outProtocol;
            conversionArg.MapRules = IntPtr.Zero;
            conversionArg.MapRuleCount = 0;
            if(mapRules.Count > 0)
            {
                var mapRuleArray = new udtMapConversionRule[mapRules.Count];
                for(var i = 0; i < mapRules.Count; ++i)
                {
                    var inputName = Marshal.StringToHGlobalAnsi(mapRules[i].InputName);
                    var outputName = Marshal.StringToHGlobalAnsi(mapRules[i].OutputName);
                    mapRuleArray[i].InputName = inputName;
                    mapRuleArray[i].OutputName = outputName;
                    mapRuleArray[i].PositionOffsetX = mapRules[i].OffsetX;
                    mapRuleArray[i].PositionOffsetY = mapRules[i].OffsetY;
                    mapRuleArray[i].PositionOffsetZ = mapRules[i].OffsetZ;
                    resources.GlobalAllocationHandles.Add(inputName);
                    resources.GlobalAllocationHandles.Add(outputName);
                }
                var pinnedMapRules = new PinnedObject(mapRuleArray);
                resources.PinnedObjects.Add(pinnedMapRules);
                conversionArg.MapRules = pinnedMapRules.Address;
                conversionArg.MapRuleCount = (UInt32)mapRuleArray.Length;
            }

            var result = udtErrorCode.OperationFailed;
            try
            {
                result = udtConvertDemoFiles(ref parseArg, ref multiParseArg, ref conversionArg);
            }
            finally
            {
                resources.Free();
            }

            return result != udtErrorCode.None;
        }
コード例 #17
0
 private static IntPtr SendLVMsg <TLP>(HWND hwnd, ListViewMessage msg, int wParam, TLP lParam) where TLP : class
 {
     using var lpin = new PinnedObject(lParam);
     return(SendMessage(hwnd, (uint)msg, (IntPtr)wParam, lpin));
 }
コード例 #18
0
ファイル: UnitTestHelper.cs プロジェクト: wushian/Vanara
 public static string Dump(object o)
 {
     using (var p = new PinnedObject(o))
         return((((IntPtr)p).ToArray <byte>(Marshal.SizeOf(o))).ToHexDumpString());
 }
コード例 #19
0
        //-------------------------------------------------------------------------
        // Function: GetLocalCloudName
        //
        // Purpose:  Retrieve first available local cloud name
        //
        // Arguments:
        //   cchCloudNameSize[in]: number of characters in pwzCloudName
        //                         (usually MAX_CLOUD_NAME)
        //   pwzCloudName [out]  : location to which cloud name will be copied
        //
        // Returns:  HRESULT
        //
        internal static HRESULT GetLocalCloudName(out string pwzCloudName)
        {
            HRESULT hr = HRESULT.S_OK;

            pwzCloudName = null;
            SafeHGlobalStruct <WSAQUERYSET> pResults = new SafeHGlobalStruct <WSAQUERYSET>(IntPtr.Zero);

            // Fill out information for WSA query
            var CloudInfo = new PNRPCLOUDINFO
            {
                dwSize = (uint)Marshal.SizeOf <PNRPCLOUDINFO>(),
                Cloud  = new PNRP_CLOUD_ID {
                    Scope = PNRP_SCOPE.PNRP_LINK_LOCAL_SCOPE
                }
            };

            using var pCloudInfo = new PinnedObject(CloudInfo);
            var blPnrpData = new BLOB
            {
                cbSize    = CloudInfo.dwSize,
                pBlobData = pCloudInfo
            };

            using var pGuid = new PinnedObject(SVCID_PNRPCLOUD);
            using var pBlob = new PinnedObject(blPnrpData);
            var querySet = new WSAQUERYSET
            {
                dwSize           = (uint)Marshal.SizeOf <WSAQUERYSET>(),
                dwNameSpace      = NS.NS_PNRPCLOUD,
                lpServiceClassId = (IntPtr)pGuid,
                lpBlob           = pBlob
            };

            var iErr = WSALookupServiceBegin(querySet, LUP.LUP_RETURN_NAME, out var hLookup);

            if (iErr.Failed)
            {
                return(iErr.ToHRESULT());
            }
            else
            {
                var  tempResultSet = new SafeHGlobalStruct <WSAQUERYSET>();
                uint dwResultSize  = tempResultSet.Size;

                // Get size of results
                iErr = WSALookupServiceNext(hLookup, 0, ref dwResultSize, tempResultSet);

                if (iErr.Failed)
                {
                    var dwErr = WSAGetLastError();

                    if (dwErr == 10014 /*WSAEFAULT*/)
                    {
                        // allocate space for results
                        pResults = new SafeHGlobalStruct <WSAQUERYSET>(dwResultSize);
                        if (pResults.IsInvalid)
                        {
                            hr = WSAGetLastError().ToHRESULT();
                        }
                    }
                    else
                    {
                        hr = dwErr.ToHRESULT();
                    }
                }
            }

            if (hr.Succeeded)
            {
                // retrieve the local cloud information
                uint dwResultSize = pResults.Size;
                iErr = WSALookupServiceNext(hLookup, 0, ref dwResultSize, pResults);
                if (iErr.Failed)
                {
                    hr = WSAGetLastError().ToHRESULT();
                }
            }

            // Copy the cloud name (if applicable) and scope ID
            if (hr.Succeeded)
            {
                pwzCloudName = pResults.Value.lpszServiceInstanceName;
                if (hr.Failed)
                {
                    DisplayHrError("Failed to copy cloud name", hr);
                }
            }

            if (!hLookup.IsNull)
            {
                WSALookupServiceEnd(hLookup);
            }

            pResults.Dispose();
            return(hr);
        }
コード例 #20
0
        //public void SetLimitSensor(string upperlimit, string lowerlimit, string programNo, string outputNo)
        //{

        //    // † There are three setting areas: a) the write settings area, b) the running area, and c) the save area.
        //    //   * Specify a) for the setting level when you want to change multiple settings. However, to reflect settings in the LJ-V operations, you have to call LJV7IF_ReflectSetting.
        //    //	 * Specify b) for the setting level when you want to change one setting but you don't mind if this setting is returned to its value prior to the change when the power is turned off.
        //    //	 * Specify c) for the setting level when you want to change one setting and you want this new value to be retained even when the power is turned off.

        //    // @Point
        //    //  As a usage example, we will show how to use SettingForm to configure settings such that sending a setting, with SettingForm using its initial values,
        //    //  will change the sampling period in the running area to "100 Hz."
        //    //  Also see the GetSetting function.


        //    // Set upper limit
        //    _depth = 0x01;						                        // Setting depth: Running settings area
        //    _targetSetting.byType = Convert.ToByte(programNo, 16);		// Setting type: Program number
        //    _targetSetting.byCategory = 0x06;	                        // Category: Output settings
        //    _targetSetting.byItem = 0x0E;		                        // Setting item: Upper limit
        //    _targetSetting.byTarget1 = Convert.ToByte(outputNo);		// Setting target 1: output number
        //    _targetSetting.byTarget2 = 0x0;		                        // Setting target 2: None
        //    _targetSetting.byTarget3 = 0x0;		                        // Setting target 3: None
        //    _targetSetting.byTarget4 = 0x0;		                        // Setting target 4: None
        //    SetLimit(Convert.ToInt16(upperlimit));

        //    uint dwError = 0;
        //    using (PinnedObject pin = new PinnedObject(_data))

        //    try
        //    {
        //        Rc rc = (Rc)NativeMethods.LJV7IF_SetSetting(_deviceID, _depth, _targetSetting, pin.Pointer, (uint)_data.Length, ref dwError);

        //        if (rc != Rc.Ok)
        //        {
        //            U.LogPopup("Cannot set upper limit on sensor");
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        U.LogPopup(ex, "Keyence_LJ_V7001_Ctrl.SetLimit error");
        //    }

        //}



        public override void SetLimit(DispSensor dispSensor, double upperLimit, double lowerLimit)
        {
            base.SetLimit(dispSensor, upperLimit, lowerLimit);

            // † There are three setting areas: a) the write settings area, b) the running area, and c) the save area.
            //   * Specify a) for the setting level when you want to change multiple settings. However, to reflect settings in the LJ-V operations, you have to call LJV7IF_ReflectSetting.
            //	 * Specify b) for the setting level when you want to change one setting but you don't mind if this setting is returned to its value prior to the change when the power is turned off.
            //	 * Specify c) for the setting level when you want to change one setting and you want this new value to be retained even when the power is turned off.

            // @Point
            //  As a usage example, we will show how to use SettingForm to configure settings such that sending a setting, with SettingForm using its initial values,
            //  will change the sampling period in the running area to "100 Hz."
            //  Also see the GetSetting function.


            // Set upper limit
            _depth = 0x01;                                              // Setting depth: Running settings area
            _targetSetting.byType     = (byte)(dispSensor.ProgramNo);   // Setting type: Program number
            _targetSetting.byCategory = 0x06;                           // Category: Output settings
            _targetSetting.byItem     = 0x0E;                           // Setting item: Upper limit
            _targetSetting.byTarget1  = (byte)(dispSensor.OutputNo);    // Setting target 1: output number
            _targetSetting.byTarget2  = 0x0;                            // Setting target 2: None
            _targetSetting.byTarget3  = 0x0;                            // Setting target 3: None
            _targetSetting.byTarget4  = 0x0;                            // Setting target 4: None
            SetLimit(upperLimit);

            uint dwError = 0;

            using (PinnedObject pin = new PinnedObject(_data))

                try
                {
                    Rc rc = (Rc)NativeMethods.LJV7IF_SetSetting(_deviceID, _depth, _targetSetting, pin.Pointer, (uint)_data.Length, ref dwError);

                    if (rc != Rc.Ok)
                    {
                        U.LogPopup("Cannot set upper limit on sensor");
                    }
                }
                catch (Exception ex)
                {
                    U.LogPopup(ex, "Keyence_LJ_V7001_Ctrl.SetLimit error");
                }



            // Set lower limit
            _depth = 0x01;                                              // Setting depth: Running settings area
            _targetSetting.byType     = (byte)(dispSensor.ProgramNo);   // Setting type: Program number
            _targetSetting.byCategory = 0x06;                           // Category: Output settings
            _targetSetting.byItem     = 0x0E;                           // Setting item: Upper limit
            _targetSetting.byTarget1  = (byte)(dispSensor.OutputNo);    // Setting target 1: output number
            _targetSetting.byTarget2  = 0x0;                            // Setting target 2: None
            _targetSetting.byTarget3  = 0x0;                            // Setting target 3: None
            _targetSetting.byTarget4  = 0x0;                            // Setting target 4: None
            SetLimit(lowerLimit);


            using (PinnedObject pin = new PinnedObject(_data))

                try
                {
                    Rc rc = (Rc)NativeMethods.LJV7IF_SetSetting(_deviceID, _depth, _targetSetting, pin.Pointer, (uint)_data.Length, ref dwError);

                    if (rc != Rc.Ok)
                    {
                        U.LogPopup("Cannot set upper limit on sensor");
                    }
                }
                catch (Exception ex)
                {
                    U.LogPopup(ex, "Keyence_LJ_V7001_Ctrl.SetLimit error");
                }
        }
コード例 #21
0
ファイル: UDT.cs プロジェクト: Danmer/uberdemotools
        public static bool CreateMultiRailPatternInfo(ref udtPatternInfo pattern, ArgumentResources resources, udtCutByMultiRailArg rules)
        {
            var pinnedRules = new PinnedObject(rules);
            resources.PinnedObjects.Add(pinnedRules);

            pattern.Type = (UInt32)udtPatternType.MultiFragRails;
            pattern.TypeSpecificInfo = pinnedRules.Address;

            return true;
        }
コード例 #22
0
ファイル: UDT.cs プロジェクト: Danmer/uberdemotools
        public static bool CutDemoByTime(udtParserContextRef context, ref udtParseArg parseArg, string filePath, int startTimeSec, int endTimeSec)
        {
            if(context == IntPtr.Zero)
            {
                return false;
            }

            parseArg.PlugInCount = 0;
            parseArg.PlugIns = IntPtr.Zero;

            var cut = new udtCut();
            cut.GameStateIndex = parseArg.GameStateIndex;
            cut.StartTimeMs = startTimeSec * 1000;
            cut.EndTimeMs = endTimeSec * 1000;
            var pinnedCut = new PinnedObject(cut);
            var cutInfo = new udtCutByTimeArg();
            cutInfo.Cuts = pinnedCut.Address;
            cutInfo.CutCount = 1;

            var success = udtCutDemoFileByTime(context, ref parseArg, ref cutInfo, filePath) == udtErrorCode.None;
            pinnedCut.Free();

            return success;
        }
コード例 #23
0
ファイル: PROPVARIANTTests.cs プロジェクト: tajbender/Vanara
        /*public void GetCF()
         * {
         *      foreach (var f in Directory.EnumerateFiles(TestCaseSources.TempDir, "*.*", SearchOption.AllDirectories))
         *      {
         *              try
         *              {
         *                      SHGetPropertyStoreFromParsingName(f, null, GETPROPERTYSTOREFLAGS.GPS_READWRITE,
         *                              Marshal.GenerateGuidForType(typeof(IPropertyStore)), out var ps);
         *                      if (ps == null) continue;
         *                      using (var pv = new PROPVARIANT())
         *                      {
         *                              ps.GetValue(PROPERTYKEY.System.Thumbnail, pv);
         *                              if (pv.IsNullOrEmpty) continue;
         *                              if (pv.vt == VARTYPE.VT_CF)
         *                                      TestContext.WriteLine(f);
         *                      }
         *                      ps = null;
         *              }
         *              catch
         *              {
         *              }
         *      }
         * }*/

        private static object GetSampleData(VARTYPE vt)
        {
            switch (vt)
            {
            case VARTYPE.VT_ARRAY | VARTYPE.VT_VARIANT:
                return(new object[] { 100, "100" });

            case VARTYPE.VT_ARRAY | VARTYPE.VT_I4:
                var sa = SafeArrayCreateVector(VARTYPE.VT_I4, 0, 4U);
                for (int i = 0; i < 4U; i++)
                {
                    using var p = new PinnedObject(i);
                    SafeArrayPutElement(sa, i, p);
                }
                return(sa);

            case VARTYPE.VT_BLOB:
                return(new BLOB {
                    cbSize = 200, pBlobData = Marshal.AllocCoTaskMem(200)
                });

            case VARTYPE.VT_CY:
            case VARTYPE.VT_BYREF | VARTYPE.VT_CY:
            case VARTYPE.VT_BYREF | VARTYPE.VT_DECIMAL:
                return(12345.6789M);

            case VARTYPE.VT_BYREF | VARTYPE.VT_VARIANT:
                return(null);

            case VARTYPE.VT_CF:
                return(new CLIPDATA("MYCUSTOMFMT"));

            case VARTYPE.VT_CLSID:
                return(Guid.NewGuid());

            case VARTYPE.VT_DATE:
            case VARTYPE.VT_BYREF | VARTYPE.VT_DATE:
                return(new DateTime(1999, 12, 31, 23, 59, 59));

            case VARTYPE.VT_DISPATCH:
                return(Activator.CreateInstance(Type.GetTypeFromProgID("Excel.Application")));

            case VARTYPE.VT_ERROR:
            case VARTYPE.VT_BYREF | VARTYPE.VT_ERROR:
                return(new Win32Error(5));

            case VARTYPE.VT_FILETIME:
                return(new DateTime(1999, 12, 31, 23, 59, 59).ToFileTimeStruct());

            case VARTYPE.VT_BYREF | VARTYPE.VT_BSTR:
                return(Marshal.StringToBSTR("string"));

            case VARTYPE.VT_BSTR:
            case VARTYPE.VT_LPSTR:
            case VARTYPE.VT_LPWSTR:
                return("string");

            case VARTYPE.VT_STORAGE:
                StgCreateStorageEx(Path.GetTempFileName(), STGM.STGM_DELETEONRELEASE | STGM.STGM_CREATE | STGM.STGM_DIRECT | STGM.STGM_READWRITE | STGM.STGM_SHARE_EXCLUSIVE, STGFMT.STGFMT_DOCFILE, 0, IntPtr.Zero, IntPtr.Zero, typeof(IStorage).GUID, out var iptr);
                return((IStorage)iptr);

            case VARTYPE.VT_STREAM:
                SHCreateStreamOnFileEx(TestCaseSources.SmallFile, STGM.STGM_READ | STGM.STGM_SHARE_EXCLUSIVE, 0, false, null, out var stm);
                return(stm);

            case VARTYPE.VT_UNKNOWN:
                return(Activator.CreateInstance(Type.GetTypeFromProgID("ADODB.Error")));

            case VARTYPE.VT_VECTOR | VARTYPE.VT_BSTR:
            case VARTYPE.VT_VECTOR | VARTYPE.VT_LPSTR:
            case VARTYPE.VT_VECTOR | VARTYPE.VT_LPWSTR:
                return(new[] { "A", "B", "C" });

            case VARTYPE.VT_VECTOR | VARTYPE.VT_CF:
                return(new[] { new CLIPDATA(), new CLIPDATA() });

            case VARTYPE.VT_VECTOR | VARTYPE.VT_CLSID:
                return(new[] { Guid.NewGuid(), Guid.NewGuid() });

            case VARTYPE.VT_VECTOR | VARTYPE.VT_CY:
                return(new[] { 12345.6789M, 98765.4321M });

            case VARTYPE.VT_VECTOR | VARTYPE.VT_DATE:
                return(new[] { new DateTime(1999, 12, 31, 23, 59, 59), new DateTime(2000, 1, 1, 0, 0, 1) });

            case VARTYPE.VT_VECTOR | VARTYPE.VT_ERROR:
                return(new[] { new Win32Error(1), new Win32Error(5) });

            case VARTYPE.VT_VECTOR | VARTYPE.VT_FILETIME:
                return(new[] { new DateTime(1999, 12, 31, 23, 59, 59).ToFileTimeStruct(), new DateTime(2000, 1, 1, 0, 0, 1).ToFileTimeStruct() });

            case VARTYPE.VT_VECTOR | VARTYPE.VT_VARIANT:
                return(new[] { new PROPVARIANT(100), new PROPVARIANT(200) });

            case VARTYPE.VT_VERSIONED_STREAM:
                return(null);

            default:
                return(null);
            }
        }
コード例 #24
0
ファイル: UDT.cs プロジェクト: Danmer/uberdemotools
        private static bool CutDemosByPatternImpl(ArgumentResources resources, ref udtParseArg parseArg, List<string> filePaths, udtPatternInfo[] patterns, CutByPatternOptions options)
        {
            var errorCodeArray = new Int32[filePaths.Count];
            var filePathArray = new IntPtr[filePaths.Count];
            for(var i = 0; i < filePaths.Count; ++i)
            {
                filePathArray[i] = Marshal.StringToHGlobalAnsi(Path.GetFullPath(filePaths[i]));
                resources.GlobalAllocationHandles.Add(filePathArray[i]);
            }

            parseArg.PlugInCount = 0;
            parseArg.PlugIns = IntPtr.Zero;

            var pinnedFilePaths = new PinnedObject(filePathArray);
            var pinnedErrorCodes = new PinnedObject(errorCodeArray);
            var multiParseArg = new udtMultiParseArg();
            multiParseArg.FileCount = (UInt32)filePathArray.Length;
            multiParseArg.FilePaths = pinnedFilePaths.Address;
            multiParseArg.OutputErrorCodes = pinnedErrorCodes.Address;
            multiParseArg.MaxThreadCount = (UInt32)options.MaxThreadCount;

            var playerNameUnmanaged = IntPtr.Zero;
            if(!string.IsNullOrEmpty(options.PlayerName))
            {
                playerNameUnmanaged = Marshal.StringToHGlobalAnsi(options.PlayerName);
                resources.GlobalAllocationHandles.Add(playerNameUnmanaged);
            }

            var pinnedPatterns = new PinnedObject(patterns);
            var cutByPatternArg = new udtCutByPatternArg();
            cutByPatternArg.StartOffsetSec = (UInt32)options.StartOffset;
            cutByPatternArg.EndOffsetSec = (UInt32)options.EndOffset;
            cutByPatternArg.Patterns = pinnedPatterns.Address;
            cutByPatternArg.PatternCount = (UInt32)patterns.Length;
            cutByPatternArg.PlayerIndex = options.PlayerIndex;
            cutByPatternArg.PlayerName = playerNameUnmanaged;
            cutByPatternArg.Flags = 0;
            if(options.MergeCutSections)
            {
                cutByPatternArg.Flags |= (UInt32)udtCutByPatternArgFlags.MergeCutSections;
            }

            resources.PinnedObjects.Add(pinnedPatterns);
            resources.PinnedObjects.Add(pinnedFilePaths);
            resources.PinnedObjects.Add(pinnedErrorCodes);

            udtErrorCode result = udtErrorCode.OperationFailed;
            try
            {
                result = udtCutDemoFilesByPattern(ref parseArg, ref multiParseArg, ref cutByPatternArg);
            }
            finally
            {
                resources.Free();
            }

            return result == udtErrorCode.None;
        }
コード例 #25
0
 public PinnedString(string s)
 {
     Obj    = new PinnedObject(s);
     Length = s != null ? s.Length : 0;
 }
コード例 #26
0
        private void GetMetadata(Stream stream, long length, out ModuleMetadata metadata, out object lifeTimeObject)
        {
            var directAccess = stream as ISupportDirectMemoryAccess;
            if (directAccess != null)
            {
                metadata = ModuleMetadata.CreateFromMetadata(directAccess.GetPointer(), (int)length);
                lifeTimeObject = stream;
                return;
            }

            PinnedObject pinnedObject;
            var memory = stream as MemoryStream;
            if (memory != null && PortableShim.MemoryStream.GetBuffer != null)
            {
                pinnedObject = new PinnedObject((byte[])PortableShim.MemoryStream.GetBuffer.Invoke(memory, null), length);
            }
            else
            {
                var array = new byte[length];
                stream.Read(array, 0, (int)length);
                pinnedObject = new PinnedObject(array, length);
            }

            metadata = ModuleMetadata.CreateFromMetadata(pinnedObject.GetPointer(), (int)length);
            lifeTimeObject = pinnedObject;
        }
コード例 #27
0
        private void GetMetadata(Stream stream, long length, out ModuleMetadata metadata, out object lifeTimeObject)
        {
            var directAccess = stream as ISupportDirectMemoryAccess;
            if (directAccess != null)
            {
                metadata = ModuleMetadata.CreateFromMetadata(directAccess.GetPointer(), (int)length);
                lifeTimeObject = stream;
                return;
            }

            PinnedObject pinnedObject;
            ArraySegment<byte> buffer;
            var memory = stream as MemoryStream;
            if (memory != null &&
                memory.TryGetBuffer(out buffer) &&
                buffer.Offset == 0)
            {
                pinnedObject = new PinnedObject(buffer.Array, buffer.Count);
            }
            else
            {
                var array = new byte[length];
                stream.Read(array, 0, (int)length);
                pinnedObject = new PinnedObject(array, length);
            }

            metadata = ModuleMetadata.CreateFromMetadata(pinnedObject.GetPointer(), (int)length);
            lifeTimeObject = pinnedObject;
        }
コード例 #28
0
        /*****************************************************************************
        *  HrCreateKey
        *
        *  This function uses the NCrypt API to open the storage provider
        *  and create the key
        *****************************************************************************/
        static HRESULT HrCreateKey(string pwszProvName, string wszContainerName, string pwszAlgid, uint dwBits, out SafeNCRYPT_KEY_HANDLE phKey)
        {
            SafeNCRYPT_PROV_HANDLE hProvider = default;
            HRESULT hr = HRESULT.S_OK;

            phKey = default;

            hr = NCryptOpenStorageProvider(out hProvider, pwszProvName ?? KnownStorageProvider.MS_KEY_STORAGE_PROVIDER);
            if (hr.Failed)
            {
                goto CleanUp;
            }

            hr = NCryptOpenKey(hProvider, out phKey, wszContainerName);
            if (hr.Succeeded)
            {
                hr = NCryptDeleteKey(phKey);
                phKey.Dispose();
                phKey = default;
                if (hr.Failed)
                {
                    goto CleanUp;
                }
            }

            hr = NCryptCreatePersistedKey(hProvider, out phKey, pwszAlgid, wszContainerName);
            if (hr.Failed)
            {
                goto CleanUp;
            }

            if (0 != dwBits)
            {
                using var pdwBits = new PinnedObject(dwBits);
                hr = NCryptSetProperty(phKey, NCrypt.PropertyName.NCRYPT_LENGTH_PROPERTY, pdwBits, (uint)Marshal.SizeOf(dwBits), SetPropFlags.NCRYPT_PERSIST_FLAG);
                if (hr.Failed)
                {
                    goto CleanUp;
                }
            }

            hr = NCryptFinalizeKey(phKey);

            if (hr.Failed)
            {
                goto CleanUp;
            }

            hr = HRESULT.S_OK;

CleanUp:

            if (hr.Failed)
            {
                phKey?.Dispose();
                phKey = null;
            }
            hProvider?.Dispose();

            return(hr);
        }
コード例 #29
0
        private void CreateHarwareAccelerationContext(GraphicsDevice graphicsDevice, AVCodecContext *pAVCodecContext, AVCodec *pCodec)
        {
            var videoDevice  = graphicsDevice?.NativeDevice?.QueryInterface <VideoDevice1>();
            var videoContext = graphicsDevice?.NativeDeviceContext?.QueryInterface <VideoContext1>();

            if (videoDevice == null || videoContext == null)
            {
                return;
            }

            foreach (var profile in FindVideoFormatCompatibleProfiles(videoDevice, *pCodec))
            {
                // Create and configure the video decoder
                var videoDecoderDescription = new VideoDecoderDescription
                {
                    Guid         = profile,
                    SampleWidth  = pAVCodecContext->width,
                    SampleHeight = pAVCodecContext->height,
                    OutputFormat = DecoderOuputFormat,
                };

                videoDevice.GetVideoDecoderConfigCount(ref videoDecoderDescription, out var configCount);
                for (var i = 0; i < configCount; ++i)
                {
                    // get and check the decoder configuration for the profile
                    videoDevice.GetVideoDecoderConfig(ref videoDecoderDescription, i, out var decoderConfig);
                    //if (check to performe on the config)
                    //    continue;

                    // create the decoder from the configuration
                    videoDevice.CreateVideoDecoder(ref videoDecoderDescription, ref decoderConfig, out videoHardwareDecoder);

                    // create the decoder output view
                    var videoDecoderOutputViewDescription = new VideoDecoderOutputViewDescription
                    {
                        DecodeProfile = profile,
                        Dimension     = VdovDimension.Texture2D,
                        Texture2D     = new Texture2DVdov {
                            ArraySlice = 0,
                        },
                    };
                    DecoderOutputTexture = Texture.New2D(graphicsDevice, pAVCodecContext->width, pAVCodecContext->height, (PixelFormat)DecoderOuputFormat, TextureFlags.RenderTarget | TextureFlags.ShaderResource);
                    videoDevice.CreateVideoDecoderOutputView(DecoderOutputTexture.NativeResource, ref videoDecoderOutputViewDescription, out videoHardwareDecoderView);

                    // Create and fill the hardware context
                    var contextd3d11 = ffmpeg.av_d3d11va_alloc_context();

                    var iVideoContext = new ID3D11VideoContext {
                        lpVtbl = (ID3D11VideoContextVtbl *)videoContext.NativePointer
                    };
                    videoContextHandle          = new PinnedObject <ID3D11VideoContext>(iVideoContext);
                    contextd3d11->video_context = (ID3D11VideoContext *)videoContextHandle.Pointer;

                    var iVideoDecoder = new ID3D11VideoDecoder {
                        lpVtbl = (ID3D11VideoDecoderVtbl *)videoHardwareDecoder.NativePointer
                    };
                    videoDecoderHandle    = new PinnedObject <ID3D11VideoDecoder>(iVideoDecoder);
                    contextd3d11->decoder = (ID3D11VideoDecoder *)videoDecoderHandle.Pointer;

                    decoderConfigHandle = new PinnedObject <D3D11_VIDEO_DECODER_CONFIG>(decoderConfig.ToFFmpegDecoderConfig());
                    contextd3d11->cfg   = (D3D11_VIDEO_DECODER_CONFIG *)decoderConfigHandle.Pointer;

                    var iVideoOutputView = new ID3D11VideoDecoderOutputView {
                        lpVtbl = (ID3D11VideoDecoderOutputViewVtbl *)videoHardwareDecoderView.NativePointer
                    };
                    decoderOuputViewsHandle     = new PinnedObject <ID3D11VideoDecoderOutputView>(iVideoOutputView, true);
                    contextd3d11->surface       = (ID3D11VideoDecoderOutputView **)decoderOuputViewsHandle.Pointer;
                    contextd3d11->surface_count = 1;

                    pAVCodecContext->hwaccel_context = contextd3d11;
                }
            }
        }