Exemplo n.º 1
0
        public FileIndex(string idxFile, string mulFile, int file)
        {
            string idxPath = null;

            MulPath = null;
            if (Files.MulPath == null)
            {
                Files.LoadMulPath();
            }
            if (Files.MulPath.Count > 0)
            {
                idxPath = Files.MulPath[idxFile.ToLower()];
                MulPath = Files.MulPath[mulFile.ToLower()];
                if (String.IsNullOrEmpty(idxPath))
                {
                    idxPath = null;
                }
                else
                {
                    if (String.IsNullOrEmpty(Path.GetDirectoryName(idxPath)))
                    {
                        idxPath = Path.Combine(Files.RootDir, idxPath);
                    }
                    if (!File.Exists(idxPath))
                    {
                        idxPath = null;
                    }
                }
                if (String.IsNullOrEmpty(MulPath))
                {
                    MulPath = null;
                }
                else
                {
                    if (String.IsNullOrEmpty(Path.GetDirectoryName(MulPath)))
                    {
                        MulPath = Path.Combine(Files.RootDir, MulPath);
                    }
                    if (!File.Exists(MulPath))
                    {
                        MulPath = null;
                    }
                }
            }

            if ((idxPath != null) && (MulPath != null))
            {
                using (FileStream index = new FileStream(idxPath, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    Stream = new FileStream(MulPath, FileMode.Open, FileAccess.Read, FileShare.Read);
                    int count = (int)(index.Length / 12);
                    IdxLength = index.Length;
                    Index     = new Entry3D[count];
                    GCHandle gc     = GCHandle.Alloc(Index, GCHandleType.Pinned);
                    byte[]   buffer = new byte[index.Length];
                    index.Read(buffer, 0, (int)index.Length);
                    Marshal.Copy(buffer, 0, gc.AddrOfPinnedObject(), (int)index.Length);
                    gc.Free();
                }
            }
            else
            {
                Stream = null;
                Index  = new Entry3D[1];
                return;
            }
            Entry5D[] patches = Verdata.Patches;

            if (file > -1)
            {
                for (int i = 0; i < patches.Length; ++i)
                {
                    Entry5D patch = patches[i];

                    if (patch.file == file && patch.index >= 0 && patch.index < Index.Length)
                    {
                        Index[patch.index].lookup = patch.lookup;
                        Index[patch.index].length = patch.length | (1 << 31);
                        Index[patch.index].extra  = patch.extra;
                    }
                }
            }
        }
Exemplo n.º 2
0
 /// <summary>
 /// For derived classes only.
 /// </summary>
 protected MidiPort()
 {
     _status           = MidiPortStatus.Closed;
     _instanceHandle   = GCHandle.Alloc(this, GCHandleType.Weak);
     AutoReturnBuffers = true;
 }
Exemplo n.º 3
0
        void Init(byte[] bios)
        {
            bool GL = SyncSettings.UseGL;

            if (AttachedCore != null)
            {
                AttachedCore.Dispose();
                AttachedCore = null;
            }
            VideoHandle = GCHandle.Alloc(VideoBuffer, GCHandleType.Pinned);
            SoundHandle = GCHandle.Alloc(SoundBuffer, GCHandleType.Pinned);

            LibYabause.CDInterface CDInt = new LibYabause.CDInterface();
            CDInt.InitFunc          = InitH = new LibYabause.CDInterface.Init(CD_Init);
            CDInt.DeInitFunc        = DeInitH = new LibYabause.CDInterface.DeInit(CD_DeInit);
            CDInt.GetStatusFunc     = GetStatusH = new LibYabause.CDInterface.GetStatus(CD_GetStatus);
            CDInt.ReadTOCFunc       = ReadTOCH = new LibYabause.CDInterface.ReadTOC(CD_ReadTOC);
            CDInt.ReadSectorFADFunc = ReadSectorFADH = new LibYabause.CDInterface.ReadSectorFAD(CD_ReadSectorFAD);
            CDInt.ReadAheadFADFunc  = ReadAheadFADH = new LibYabause.CDInterface.ReadAheadFAD(CD_ReadAheadFAD);

            var    fp       = new FilePiping();
            string BiosPipe = fp.GetPipeNameNative();

            fp.Offer(bios);

            int basetime;

            if (SyncSettings.RealTimeRTC)
            {
                basetime = 0;
            }
            else
            {
                basetime = (int)((SyncSettings.RTCInitialTime - new DateTime(1970, 1, 1).ToLocalTime()).TotalSeconds);
            }

            if (!LibYabause.libyabause_init
                (
                    ref CDInt,
                    BiosPipe,
                    GL,
                    SyncSettings.CartType,
                    SyncSettings.SkipBios,
                    !SyncSettings.RealTimeRTC,
                    basetime
                ))
            {
                throw new Exception("libyabause_init() failed!");
            }

            fp.Finish();

            LibYabause.libyabause_setvidbuff(VideoHandle.AddrOfPinnedObject());
            LibYabause.libyabause_setsndbuff(SoundHandle.AddrOfPinnedObject());
            AttachedCore = this;

            // with or without GL, this is the guaranteed frame -1 size; (unless you do a gl resize)
            BufferWidth  = 320;
            BufferHeight = 224;

            InitMemoryDomains();

            GLMode = GL;
            // if in GL mode, this will trigger the initial GL resize
            PutSyncSettings(this.SyncSettings);
        }
Exemplo n.º 4
0
 internal Watcher(LibEvLoop loop) : base(loop)
 {
     Loop      = loop;
     gc_handle = GCHandle.Alloc(this);
 }
Exemplo n.º 5
0
        public T Read <T>(IntPtr address) where T : struct
        {
            object ret    = default(T);
            var    buffer = new byte[0];

            if (typeof(T) == typeof(string))
            {
                return((T)(object)ReadCString(address));
            }
            buffer = ReadBytes(address, (uint)Marshal.SizeOf(typeof(T)));

            switch (Type.GetTypeCode(typeof(T)))
            {
            case TypeCode.Object:
                GCHandle handle = GCHandle.Alloc(buffer, GCHandleType.Pinned);
                Marshal.PtrToStructure(handle.AddrOfPinnedObject(), ret);
                handle.Free();
                break;

            case TypeCode.Boolean:
                ret = BitConverter.ToBoolean(buffer, 0);
                break;

            case TypeCode.Char:
                ret = BitConverter.ToChar(buffer, 0);
                break;

            case TypeCode.Byte:
                ret = buffer[0];
                break;

            case TypeCode.Int16:
                ret = BitConverter.ToInt16(buffer, 0);
                break;

            case TypeCode.UInt16:
                ret = BitConverter.ToUInt16(buffer, 0);
                break;

            case TypeCode.Int32:
                ret = BitConverter.ToInt32(buffer, 0);
                break;

            case TypeCode.UInt32:
                ret = BitConverter.ToUInt32(buffer, 0);
                break;

            case TypeCode.Int64:
                ret = BitConverter.ToInt64(buffer, 0);
                break;

            case TypeCode.UInt64:
                ret = BitConverter.ToUInt64(buffer, 0);
                break;

            case TypeCode.Single:
                ret = BitConverter.ToSingle(buffer, 0);
                break;

            case TypeCode.Double:
                ret = BitConverter.ToDouble(buffer, 0);
                break;

            default:
                throw new NotSupportedException($"Unknown type {typeof(T).Name}.");
            }

            return((T)ret);
        }
 public HandleTracked(T item)
 {
     _gcHandle = GCHandle.Alloc(item);
 }
Exemplo n.º 7
0
        internal ECDsaCng CreateECDsa(string algorithm, bool usePrivateKey)
        {
            if (Crv == null)
                throw LogHelper.LogArgumentNullException(nameof(Crv));

            if (X == null)
                throw LogHelper.LogArgumentNullException(nameof(X));

            if (Y == null)
                throw LogHelper.LogArgumentNullException(nameof(Y));

            GCHandle keyBlobHandle = new GCHandle();
            try
            {
                uint dwMagic = GetMagicValue(Crv, usePrivateKey);
                uint cbKey = GetKeyByteCount(Crv);
                byte[] keyBlob;
#if NET45
                if (usePrivateKey)
                    keyBlob = new byte[3 * cbKey + 2 * Marshal.SizeOf(typeof(uint))];
                else
                    keyBlob = new byte[2 * cbKey + 2 * Marshal.SizeOf(typeof(uint))];
#else
                 if (usePrivateKey)
                     keyBlob = new byte[3 * cbKey + 2 * Marshal.SizeOf<uint>()];
                 else
                     keyBlob = new byte[2 * cbKey + 2 * Marshal.SizeOf<uint>()];
#endif
                keyBlobHandle = GCHandle.Alloc(keyBlob, GCHandleType.Pinned);
                IntPtr keyBlobPtr = keyBlobHandle.AddrOfPinnedObject();
                byte[] x = Base64UrlEncoder.DecodeBytes(X);
                byte[] y = Base64UrlEncoder.DecodeBytes(Y);

                Marshal.WriteInt64(keyBlobPtr, 0, dwMagic);
                Marshal.WriteInt64(keyBlobPtr, 4, cbKey);

                int index = 8;
                foreach (byte b in x)
                    Marshal.WriteByte(keyBlobPtr, index++, b);

                foreach (byte b in y)
                    Marshal.WriteByte(keyBlobPtr, index++, b);

                if (usePrivateKey)
                {
                    if (D == null)
                        throw LogHelper.LogArgumentNullException(nameof(D));

                    byte[] d = Base64UrlEncoder.DecodeBytes(D);
                    foreach (byte b in d)
                        Marshal.WriteByte(keyBlobPtr, index++, b);

                    Marshal.Copy(keyBlobPtr, keyBlob, 0, keyBlob.Length);
                    using (CngKey cngKey = CngKey.Import(keyBlob, CngKeyBlobFormat.EccPrivateBlob))
                    {
                        if (Utility.ValidateECDSAKeySize(cngKey.KeySize, algorithm))
                            return new ECDsaCng(cngKey);
                        else
                            throw LogHelper.LogExceptionMessage(new ArgumentOutOfRangeException("key.KeySize", String.Format(CultureInfo.InvariantCulture, LogMessages.IDX10671, cngKey, ECDsaAlgorithm.DefaultECDsaKeySizeInBitsMap[algorithm], cngKey.KeySize)));
                    }
                }
                else
                {
                    Marshal.Copy(keyBlobPtr, keyBlob, 0, keyBlob.Length);
                    using (CngKey cngKey = CngKey.Import(keyBlob, CngKeyBlobFormat.EccPublicBlob))
                    {
                        if (Utility.ValidateECDSAKeySize(cngKey.KeySize, algorithm))
                            return new ECDsaCng(cngKey);
                        else
                            throw LogHelper.LogExceptionMessage(new ArgumentOutOfRangeException("key.KeySize", String.Format(CultureInfo.InvariantCulture, LogMessages.IDX10671, cngKey, ECDsaAlgorithm.DefaultECDsaKeySizeInBitsMap[algorithm], cngKey.KeySize)));
                    }
                }
            }
            finally
            {
                if (keyBlobHandle != null)
                    keyBlobHandle.Free();
            }
        }
Exemplo n.º 8
0
        internal unsafe void SendError(ulong requestId, int httpStatusCode, IList <string> authChallenges = null)
        {
            HttpApiTypes.HTTP_RESPONSE_V2 httpResponse = new HttpApiTypes.HTTP_RESPONSE_V2();
            httpResponse.Response_V1.Version = new HttpApiTypes.HTTP_VERSION();
            httpResponse.Response_V1.Version.MajorVersion = (ushort)1;
            httpResponse.Response_V1.Version.MinorVersion = (ushort)1;

            List <GCHandle> pinnedHeaders = null;
            GCHandle        gcHandle;

            try
            {
                // Copied from the multi-value headers section of SerializeHeaders
                if (authChallenges != null && authChallenges.Count > 0)
                {
                    pinnedHeaders = new List <GCHandle>(authChallenges.Count + 3);

                    HttpApiTypes.HTTP_RESPONSE_INFO[] knownHeaderInfo = null;
                    knownHeaderInfo = new HttpApiTypes.HTTP_RESPONSE_INFO[1];
                    gcHandle        = GCHandle.Alloc(knownHeaderInfo, GCHandleType.Pinned);
                    pinnedHeaders.Add(gcHandle);
                    httpResponse.pResponseInfo = (HttpApiTypes.HTTP_RESPONSE_INFO *)gcHandle.AddrOfPinnedObject();

                    knownHeaderInfo[httpResponse.ResponseInfoCount].Type   = HttpApiTypes.HTTP_RESPONSE_INFO_TYPE.HttpResponseInfoTypeMultipleKnownHeaders;
                    knownHeaderInfo[httpResponse.ResponseInfoCount].Length =
                        (uint)Marshal.SizeOf <HttpApiTypes.HTTP_MULTIPLE_KNOWN_HEADERS>();

                    HttpApiTypes.HTTP_MULTIPLE_KNOWN_HEADERS header = new HttpApiTypes.HTTP_MULTIPLE_KNOWN_HEADERS();

                    header.HeaderId = HttpApiTypes.HTTP_RESPONSE_HEADER_ID.Enum.HttpHeaderWwwAuthenticate;
                    header.Flags    = HttpApiTypes.HTTP_RESPONSE_INFO_FLAGS.PreserveOrder; // The docs say this is for www-auth only.

                    HttpApiTypes.HTTP_KNOWN_HEADER[] nativeHeaderValues = new HttpApiTypes.HTTP_KNOWN_HEADER[authChallenges.Count];
                    gcHandle = GCHandle.Alloc(nativeHeaderValues, GCHandleType.Pinned);
                    pinnedHeaders.Add(gcHandle);
                    header.KnownHeaders = (HttpApiTypes.HTTP_KNOWN_HEADER *)gcHandle.AddrOfPinnedObject();

                    for (int headerValueIndex = 0; headerValueIndex < authChallenges.Count; headerValueIndex++)
                    {
                        // Add Value
                        string headerValue = authChallenges[headerValueIndex];
                        byte[] bytes       = HeaderEncoding.GetBytes(headerValue);
                        nativeHeaderValues[header.KnownHeaderCount].RawValueLength = (ushort)bytes.Length;
                        gcHandle = GCHandle.Alloc(bytes, GCHandleType.Pinned);
                        pinnedHeaders.Add(gcHandle);
                        nativeHeaderValues[header.KnownHeaderCount].pRawValue = (byte *)gcHandle.AddrOfPinnedObject();
                        header.KnownHeaderCount++;
                    }

                    // This type is a struct, not an object, so pinning it causes a boxed copy to be created. We can't do that until after all the fields are set.
                    gcHandle = GCHandle.Alloc(header, GCHandleType.Pinned);
                    pinnedHeaders.Add(gcHandle);
                    knownHeaderInfo[0].pInfo = (HttpApiTypes.HTTP_MULTIPLE_KNOWN_HEADERS *)gcHandle.AddrOfPinnedObject();

                    httpResponse.ResponseInfoCount = 1;
                }

                httpResponse.Response_V1.StatusCode = (ushort)httpStatusCode;
                string statusDescription = HttpReasonPhrase.Get(httpStatusCode);
                uint   dataWritten       = 0;
                uint   statusCode;
                byte[] byteReason = HeaderEncoding.GetBytes(statusDescription);
                fixed(byte *pReason = byteReason)
                {
                    httpResponse.Response_V1.pReason      = (byte *)pReason;
                    httpResponse.Response_V1.ReasonLength = (ushort)byteReason.Length;

                    byte[] byteContentLength = new byte[] { (byte)'0' };
                    fixed(byte *pContentLength = byteContentLength)
                    {
                        (&httpResponse.Response_V1.Headers.KnownHeaders)[(int)HttpSysResponseHeader.ContentLength].pRawValue      = (byte *)pContentLength;
                        (&httpResponse.Response_V1.Headers.KnownHeaders)[(int)HttpSysResponseHeader.ContentLength].RawValueLength = (ushort)byteContentLength.Length;
                        httpResponse.Response_V1.Headers.UnknownHeaderCount = 0;

                        statusCode =
                            HttpApi.HttpSendHttpResponse(
                                _requestQueue.Handle,
                                requestId,
                                0,
                                &httpResponse,
                                null,
                                &dataWritten,
                                IntPtr.Zero,
                                0,
                                SafeNativeOverlapped.Zero,
                                IntPtr.Zero);
                    }
                }
                if (statusCode != UnsafeNclNativeMethods.ErrorCodes.ERROR_SUCCESS)
                {
                    // if we fail to send a 401 something's seriously wrong, abort the request
                    HttpApi.HttpCancelHttpRequest(_requestQueue.Handle, requestId, IntPtr.Zero);
                }
            }
            finally
            {
                if (pinnedHeaders != null)
                {
                    foreach (GCHandle handle in pinnedHeaders)
                    {
                        if (handle.IsAllocated)
                        {
                            handle.Free();
                        }
                    }
                }
            }
        }
Exemplo n.º 9
0
        /// <summary>
        /// Enumerates computers on the local network.
        /// </summary>
        private void OnEnumerate(object state)
        {
            IntPtr pInfo;

            int entriesRead  = 0;
            int totalEntries = 0;
            int resumeHandle = 0;
            int result       = ERROR_MORE_DATA;

            GCHandle dwResumeHandle = GCHandle.Alloc(resumeHandle, GCHandleType.Pinned);

            try
            {
                while (m_stopped == 0 && result == ERROR_MORE_DATA)
                {
                    // enumerate the first batch of servers.
                    result = NetServerEnum(
                        IntPtr.Zero,
                        LEVEL_SERVER_INFO_100,
                        out pInfo,
                        MAX_PREFERRED_LENGTH,
                        out entriesRead,
                        out totalEntries,
                        SV_TYPE_WORKSTATION | SV_TYPE_SERVER,
                        m_domain,
                        dwResumeHandle.AddrOfPinnedObject());

                    // check for fatal error.
                    if ((result != NERR_Success) && (result != ERROR_MORE_DATA))
                    {
                        Utils.Trace("Could not enumerate hosts on network. Error = {0}", result);
                        return;
                    }

                    // copy host names from the returned structures.
                    string[] hostnames = new string[entriesRead];

                    IntPtr pos = pInfo;

                    for (int ii = 0; ii < entriesRead; ii++)
                    {
                        SERVER_INFO_100 info = (SERVER_INFO_100)Marshal.PtrToStructure(pos, typeof(SERVER_INFO_100));

                        hostnames[ii] = info.sv100_name;

                        pos = (IntPtr)(pos.ToInt64() + Marshal.SizeOf(typeof(SERVER_INFO_100)));
                    }

                    NetApiBufferFree(pInfo);

                    // raise an event.
                    if (m_stopped == 0 && m_HostsDiscovered != null)
                    {
                        try
                        {
                            m_HostsDiscovered(this, new HostEnumeratorEventArgs(hostnames));
                        }
                        catch (Exception e)
                        {
                            Utils.Trace(e, "Unexpected exception raising HostsDiscovered event.");
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Utils.Trace(e, "Unexpected exception calling NetServerEnum.");
            }
            finally
            {
                if (dwResumeHandle.IsAllocated)
                {
                    dwResumeHandle.Free();
                }
            }
        }
Exemplo n.º 10
0
        public static List <bioapi_unit_schema> EnumerateDevices()
        {
            uint res;
            List <bioapi_unit_schema> result = new List <bioapi_unit_schema>();
            bioapi_unit_schema        unitinfo;

            GCHandle gch = GCHandle.Alloc(_bspinfo.BSPUuid, GCHandleType.Pinned);

            try
            {
                res = BioAPI.OK;
                if (BSPLoaded)
                {
                    try
                    {
                        res = BioAPI.BSPUnload(gch.AddrOfPinnedObject(), (BioAPI.EventHandler)null, IntPtr.Zero);
                    }
                    catch (Exception ex)
                    {
                        _log.Error(ex);
                    }
                }
                if (res == BioAPI.OK)
                {
                    BSPLoaded = false;
                    res       = BioAPI.BSPLoad(gch.AddrOfPinnedObject(), (BioAPI.EventHandler)null, IntPtr.Zero);
                    if (res == BioAPI.OK)
                    {
                        BSPLoaded = true;
                        res       = BioAPI.QueryUnits(gch.AddrOfPinnedObject(), ref DeviceArray, ref deviceCount);
                        if (res == BioAPI.OK)
                        {
                            for (int i = 0; i < deviceCount; i++)
                            {
                                int size = Marshal.SizeOf(typeof(bioapi_unit_schema));
                                unitinfo = (bioapi_unit_schema)Marshal.PtrToStructure(DeviceArray + size * i, typeof(bioapi_unit_schema));
                                result.Add(unitinfo);
                            }
                        }
                        else
                        {
                            throw new Exception("QueryUnits " + res.ToString());
                        }
                    }
                    else
                    {
                        throw new Exception("BSPLoad " + res.ToString());
                    }
                }
                else
                {
                    throw new Exception("BSPUnload " + res.ToString());
                }
            }
            catch (Exception ex)
            {
                _log.Error(ex);
            }
            finally
            {
                gch.Free();
            }
            return(result);
        }
Exemplo n.º 11
0
        public void CreateDeploymentData(BackgroundWorker backgroundWorker, DoWorkEventArgs doWorkEventArgs)
        {
            MFDevice device = doWorkEventArgs.Argument as MFDevice;

            _DBG.Engine eng = device.DbgEngine;

            Commands.Monitor_FlashSectorMap.Reply flashMap = eng.GetFlashSectorMap();

            //find deployment sectors.
            MemoryStream deploymentStream = new MemoryStream();

            //this duplicates LoadDeploymentAssemblies logic, as how to find assemblies in the deployment sectors
            int  iSectorStart = -1, iSectorEnd = 0;
            uint address, addressAssemblyStart, addressStart = 0, addressEnd = 0;
            int  iSector;

            //First, find out where the deployment sectors are
            for (iSector = 0; iSector < flashMap.m_map.Length; iSector++)
            {
                Commands.Monitor_FlashSectorMap.FlashSectorData flashSectorData = flashMap.m_map[iSector];
                if ((flashSectorData.m_flags & Commands.Monitor_FlashSectorMap.c_MEMORY_USAGE_MASK) == Commands.Monitor_FlashSectorMap.c_MEMORY_USAGE_DEPLOYMENT)
                {
                    if (iSectorStart < 0)
                    {
                        iSectorStart = iSector;
                        addressStart = flashSectorData.m_address;
                    }

                    iSectorEnd = iSector;
                    addressEnd = flashSectorData.m_address + flashSectorData.m_size;
                }
            }

            if (iSectorStart < 0)
            {
                throw new ApplicationException("Could not find deployment sectors");
            }

            address = addressStart;
            iSector = iSectorStart;

            while (true)
            {
                if (backgroundWorker.WorkerReportsProgress)
                {
                    int progress = (int)(100.0 * (double)address / (double)addressEnd);
                    backgroundWorker.ReportProgress(progress);
                }

                //read assembly header
                uint   assemblyHeaderSize  = (uint)Marshal.SizeOf(typeof(CLR_RECORD_ASSEMBLY));
                byte[] assemblyHeaderBytes = null;
                byte[] assemblyDataBytes   = null;

                if (address + assemblyHeaderSize >= addressEnd)
                {
                    break;
                }

                addressAssemblyStart = address;

                if (!CreateDeploymentReadHelper(backgroundWorker, doWorkEventArgs, eng, ref address, addressStart, addressEnd, assemblyHeaderSize, out assemblyHeaderBytes))
                {
                    return;
                }

                GCHandle            gch            = GCHandle.Alloc(assemblyHeaderBytes, GCHandleType.Pinned);
                CLR_RECORD_ASSEMBLY assemblyHeader = (CLR_RECORD_ASSEMBLY)Marshal.PtrToStructure(gch.AddrOfPinnedObject(), typeof(CLR_RECORD_ASSEMBLY));
                gch.Free();

                //check if valid header
                //check marker
                bool fValidAssembly = assemblyHeader.marker == CLR_RECORD_ASSEMBLY.MARKER_ASSEMBLY_V1;

                if (fValidAssembly)
                {
                    //check header crc
                    uint crcHeader = assemblyHeader.headerCRC;

                    //clear headerCRC
                    int headerCRCOffset = 8;
                    int headerCRCSize   = 4;

                    Array.Clear(assemblyHeaderBytes, headerCRCOffset, headerCRCSize);

                    uint crc = _DBG.CRC.ComputeCRC(assemblyHeaderBytes, 0);

                    //Reset headerCRC
                    Array.Copy(BitConverter.GetBytes(crcHeader), 0, assemblyHeaderBytes, headerCRCOffset, headerCRCSize);

                    fValidAssembly = (crcHeader == crc);
                }

                if (fValidAssembly)
                {
                    uint assemblyTotalSize = assemblyHeader.startOfTables[CLR_RECORD_ASSEMBLY.TBL_EndOfAssembly];
                    uint assemblyDataSize  = assemblyTotalSize - assemblyHeaderSize;

                    if (address + assemblyDataSize >= addressEnd)
                    {
                        break;
                    }

                    //read body
                    if (!CreateDeploymentReadHelper(backgroundWorker, doWorkEventArgs, eng, ref address, addressStart, addressEnd, assemblyDataSize, out assemblyDataBytes))
                    {
                        return;
                    }

                    //check if valid body (crc)
                    uint crc = _DBG.CRC.ComputeCRC(assemblyDataBytes, 0);

                    fValidAssembly = (crc == assemblyHeader.assemblyCRC);
                }

                if (fValidAssembly)
                {
                    // add to compact stream
                    deploymentStream.Write(assemblyHeaderBytes, 0, assemblyHeaderBytes.Length);
                    deploymentStream.Write(assemblyDataBytes, 0, assemblyDataBytes.Length);

                    // make sure we are on 4 byte boundary
                    if (0 != (address % sizeof(UInt32)))
                    {
                        byte[] buff = new byte[sizeof(UInt32) - (address % sizeof(UInt32))];
                        deploymentStream.Write(buff, 0, buff.Length);
                        address += sizeof(UInt32) - (address % sizeof(UInt32));
                    }
                }
                else
                {
                    //if no, clear assemblyData, jump to next sector (if in middle of sector), or finish (if at beginning of sector)
                    while (iSector < iSectorEnd)
                    {
                        Commands.Monitor_FlashSectorMap.FlashSectorData flashSectorData = flashMap.m_map[iSector];

                        if (addressAssemblyStart >= flashSectorData.m_address && addressAssemblyStart < flashSectorData.m_address + flashSectorData.m_size)
                        {
                            // jump to next sector
                            address = flashSectorData.m_address + flashSectorData.m_size;

                            System.Diagnostics.Debug.Assert(address == flashMap.m_map[iSector + 1].m_address);

                            break;
                        }

                        iSector++;
                    }
                }
            }

            //Finished reading

            //convert to srec
            MFApplicationDeploymentData data = new MFApplicationDeploymentData();
            long deploymentLength            = deploymentStream.Seek(0, SeekOrigin.Current);

            MemoryStream streamSrec = new MemoryStream();

            deploymentStream.Seek(0, SeekOrigin.Begin);
            data.BinaryData = new byte[(int)deploymentLength];
            deploymentStream.Read(data.BinaryData, 0, (int)deploymentLength);
            deploymentStream.Seek(0, SeekOrigin.Begin);
            new BinToSrec().DoConversion(deploymentStream, streamSrec, flashMap.m_map[iSectorStart].m_address);

            //add zero bytes to all other deployment sectors?

            //Get bytes
            long pos = streamSrec.Seek(0, SeekOrigin.Current);

            data.HexData = new byte[pos];
            streamSrec.Seek(0, SeekOrigin.Begin);
            streamSrec.Read(data.HexData, 0, (int)pos);

            doWorkEventArgs.Result = data;
        }
Exemplo n.º 12
0
        private void Switch_1(int row, int col)
        {
            sight_row = row;
            sight_col = col;
            block_row = null;
            block_col = null;
            int BigWidth = 64;

            byte[] bytes = new byte[49152];
            paint.Children.Clear();
            for (int i = 0; i < 128; i++)
            {
                for (int j = 0; j < 128; j++)
                {
                    /*
                     * System.Windows.Shapes.Rectangle pixel = new System.Windows.Shapes.Rectangle();
                     * pixel.Fill = new SolidColorBrush(this.colors[col * 128 + i, row * 128 + j]);
                     * pixel.Stroke = new SolidColorBrush(this.colors[col * 128 + i, row * 128 + j]);
                     * pixel.Width = width;
                     * pixel.Height = width;
                     * pixel.SetValue(Canvas.LeftProperty, j * width + 0.0);
                     * pixel.SetValue(Canvas.TopProperty, i * width + 0.0);
                     * paint.Children.Add(pixel);
                     */
                    bytes[49151 - (i * 128 + (127 - j)) * 3] = this.colors[row * 128 + i, col * 128 + j].R;
                    bytes[49150 - (i * 128 + (127 - j)) * 3] = this.colors[row * 128 + i, col * 128 + j].G;
                    bytes[49149 - (i * 128 + (127 - j)) * 3] = this.colors[row * 128 + i, col * 128 + j].B;
                }
            }

            int      stride = 384;
            GCHandle handle = GCHandle.Alloc(bytes, GCHandleType.Pinned);
            int      scan0  = (int)handle.AddrOfPinnedObject();

            scan0 += 127 * stride;
            Bitmap bitmap = new Bitmap(128, 128, -stride, System.Drawing.Imaging.PixelFormat.Format24bppRgb, (IntPtr)scan0);

            handle.Free();

            System.Windows.Controls.Image img = new System.Windows.Controls.Image();
            MemoryStream Ms = new MemoryStream();

            bitmap.Save(Ms, System.Drawing.Imaging.ImageFormat.Bmp);
            Ms.Position = 0;
            BitmapImage ObjBitmapImage = new BitmapImage();

            ObjBitmapImage.BeginInit();
            ObjBitmapImage.StreamSource = Ms;
            ObjBitmapImage.EndInit();
            img.Source  = ObjBitmapImage;
            img.Width   = 512;
            img.Height  = 512;
            img.Stretch = Stretch.Uniform;
            paint.Children.Add(img);
            for (int i = 0; i < 8; i++)
            {
                for (int j = 0; j < 8; j++)
                {
                    System.Windows.Shapes.Rectangle pixel = new System.Windows.Shapes.Rectangle();
                    pixel.Fill   = new SolidColorBrush(System.Windows.Media.Color.FromArgb(0, 255, 255, 255));
                    pixel.Width  = BigWidth;
                    pixel.Height = BigWidth;
                    pixel.SetValue(Canvas.LeftProperty, j * BigWidth + 0.0);
                    pixel.SetValue(Canvas.TopProperty, i * BigWidth + 0.0);
                    pixel.SetValue(Panel.ZIndexProperty, 1);
                    pixel.MouseEnter        += RectangleEnter;
                    pixel.MouseMove         += RectangleEnter;
                    pixel.MouseLeave        += RectangleLeave;
                    pixel.MouseLeftButtonUp += RectanglePress;
                    paint.Children.Add(pixel);
                }
            }
            this.mode = 1;
        }
Exemplo n.º 13
0
        private void Switch_0()
        {
            sight_row = null;
            sight_col = null;
            block_row = null;
            block_col = null;
            int    row_adjust = row * 128;
            int    col_adjust = colume * 128;
            double top        = row_adjust > col_adjust ? 512.0 * (row_adjust - col_adjust) / row_adjust / 2 : 0;
            double left       = col_adjust > row_adjust ? 512.0 * (col_adjust - row_adjust) / col_adjust / 2 : 0;
            double width      = row_adjust > col_adjust ? 512.0 / (double)row_adjust : 512.0 / (double)col_adjust;
            double BigWidth   = width * 128.0;

            byte[] bytes = new byte[3 * row_adjust * col_adjust];
            paint.Children.Clear();
            for (int i = 0; i < col_adjust; i++)
            {
                for (int j = 0; j < row_adjust; j++)
                {
                    bytes[3 * row_adjust * col_adjust - (i * row_adjust + (row_adjust - j - 1)) * 3 - 1] = this.colors[i, j].R;
                    bytes[3 * row_adjust * col_adjust - (i * row_adjust + (row_adjust - j - 1)) * 3 - 2] = this.colors[i, j].G;
                    bytes[3 * row_adjust * col_adjust - (i * row_adjust + (row_adjust - j - 1)) * 3 - 3] = this.colors[i, j].B;
                }
            }

            int      stride = row_adjust * 3;
            GCHandle handle = GCHandle.Alloc(bytes, GCHandleType.Pinned);
            int      scan0  = (int)handle.AddrOfPinnedObject();

            scan0 += (col_adjust - 1) * stride;
            Bitmap bitmap = new Bitmap(row_adjust, col_adjust, -stride, System.Drawing.Imaging.PixelFormat.Format24bppRgb, (IntPtr)scan0);

            handle.Free();

            System.Windows.Controls.Image img = new System.Windows.Controls.Image();
            MemoryStream Ms = new MemoryStream();

            bitmap.Save(Ms, System.Drawing.Imaging.ImageFormat.Bmp);
            Ms.Position = 0;
            BitmapImage ObjBitmapImage = new BitmapImage();

            ObjBitmapImage.BeginInit();
            ObjBitmapImage.StreamSource = Ms;
            ObjBitmapImage.EndInit();
            img.Source  = ObjBitmapImage;
            img.Width   = 512;
            img.Height  = 512;
            img.Stretch = Stretch.Uniform;
            paint.Children.Add(img);
            for (int i = 0; i < colume; i++)
            {
                for (int j = 0; j < row; j++)
                {
                    System.Windows.Shapes.Rectangle pixel = new System.Windows.Shapes.Rectangle();
                    pixel.Fill   = new SolidColorBrush(System.Windows.Media.Color.FromArgb(0, 255, 255, 255));
                    pixel.Width  = BigWidth;
                    pixel.Height = BigWidth;
                    pixel.SetValue(Canvas.LeftProperty, left + j * BigWidth);
                    pixel.SetValue(Canvas.TopProperty, top + i * BigWidth);
                    pixel.SetValue(Panel.ZIndexProperty, 1);
                    pixel.MouseEnter        += RectangleEnter;
                    pixel.MouseMove         += RectangleEnter;
                    pixel.MouseLeave        += RectangleLeave;
                    pixel.MouseLeftButtonUp += RectanglePress;
                    paint.Children.Add(pixel);
                }
            }
            this.mode = 0;
        }
 public CpProxyUpnpOrgContentDirectory1(CpDevice aDevice)
 {
     iHandle = CpProxyUpnpOrgContentDirectory1Create(aDevice.Handle());
     iGch    = GCHandle.Alloc(this);
 }
Exemplo n.º 15
0
        internal void Initialize()
        {
            adapter = DeviceEnumerator.GetAdapter(int.Parse(Settings.Model.AdapterId));
            output  = adapter.GetOutput1(Settings.Model.DisplayId);

            var scale        = Settings.Model.Scale;
            var bounds       = output.Description.DesktopBounds;
            var outputWidth  = bounds.Right - bounds.Left;
            var outputHeight = bounds.Bottom - bounds.Top;

            renderBounds = new Rectangle(0, 0, outputWidth / scale, outputHeight / scale);
            fpsLocation  = new RectangleF(renderBounds.Width - 92, renderBounds.Height - 19, renderBounds.Width, renderBounds.Height);

            device = new Device(adapter, DeviceCreationFlags.PreventAlteringLayerSettingsFromRegistry
                                | DeviceCreationFlags.SingleThreaded
                                | DeviceCreationFlags.BgraSupport);

            gpuTexture = new Texture2D(device, new TextureDescription()
            {
                CpuAccessFlags    = CpuAccessFlags.None,
                BindFlags         = BindFlags.RenderTarget | BindFlags.ShaderResource,
                Format            = Format.B8G8R8A8_UNorm,
                Width             = outputWidth,
                Height            = outputHeight,
                OptionFlags       = ResourceOptionFlags.GenerateMipMaps,
                MipLevels         = (int)Math.Log2(scale) + 1,
                ArraySize         = 1,
                SampleDescription = { Count = 1, Quality = 0 },
                Usage             = ResourceUsage.Default
            });

            cpuTexture = new Texture2D(device, new TextureDescription()
            {
                CpuAccessFlags    = CpuAccessFlags.Read,
                BindFlags         = BindFlags.None,
                Format            = Format.B8G8R8A8_UNorm,
                Width             = renderBounds.Width,
                Height            = renderBounds.Height,
                OptionFlags       = ResourceOptionFlags.None,
                MipLevels         = 1,
                ArraySize         = 1,
                SampleDescription = { Count = 1, Quality = 0 },
                Usage             = ResourceUsage.Staging
            });

            renderDescription = new SwapChainDescription1()
            {
                BufferCount       = 1,
                Width             = renderBounds.Width,
                Stereo            = false,
                Height            = renderBounds.Height,
                Format            = Format.B8G8R8A8_UNorm,
                SampleDescription = new SampleDescription(1, 0),
                Usage             = Usage.BackBuffer | Usage.RenderTargetOutput,
                Scaling           = Scaling.Stretch,
                SwapEffect        = SwapEffect.Discard
            };

            memBuffer       = new byte[renderBounds.Height * renderBounds.Width * 4];
            pinnedMemBuffer = GCHandle.Alloc(memBuffer, GCHandleType.Pinned);
            ptrMemBuffer    = pinnedMemBuffer.AddrOfPinnedObject();

            generateRecPoints();
            Settings.Model.PropertyChanged += LedsChanged;

            duplicator = output.DuplicateOutput(device);
            scaler     = new ShaderResourceView(device, gpuTexture);
        }
Exemplo n.º 16
0
        /// <summary>
        /// Create the writer indicating Metadata information
        /// </summary>
        /// <param name="output"><see cref="System.IO.Stream"/> Where resulting WMA string will be written</param>
        /// <param name="format">PCM format of input data received in <see cref="WmaWriter.Write"/> method</param>
        /// <param name="profile">IWMProfile that describe the resulting compressed stream</param>
        /// <param name="MetadataAttributes">Array of <see cref="Yeti.WMFSdk.WM_Attr"/> structures describing the metadata information that will be in the result stream</param>
        public WmaWriter(Stream output, WaveFormat format, IWMProfile profile, WM_Attr[] MetadataAttributes)
            : base(output, format)

        {
            m_Writer = WM.CreateWriter();

            IWMWriterAdvanced wa = (IWMWriterAdvanced)m_Writer;

            wa.AddSink((IWMWriterSink)this);

            m_Writer.SetProfile(profile);

            uint inputs;

            m_Writer.GetInputCount(out inputs);

            if (inputs == 1)

            {
                IWMInputMediaProps InpProps;

                Guid type;

                m_Writer.GetInputProps(0, out InpProps);

                InpProps.GetType(out type);

                if (type == MediaTypes.WMMEDIATYPE_Audio)

                {
                    WM_MEDIA_TYPE mt;

                    mt.majortype = MediaTypes.WMMEDIATYPE_Audio;

                    mt.subtype = MediaTypes.WMMEDIASUBTYPE_PCM;

                    mt.bFixedSizeSamples = true;

                    mt.bTemporalCompression = false;

                    mt.lSampleSize = (uint)m_InputDataFormat.nBlockAlign;

                    mt.formattype = MediaTypes.WMFORMAT_WaveFormatEx;

                    mt.pUnk = IntPtr.Zero;

                    mt.cbFormat = (uint)Marshal.SizeOf(m_InputDataFormat);


                    GCHandle h = GCHandle.Alloc(m_InputDataFormat, GCHandleType.Pinned);

                    try

                    {
                        mt.pbFormat = h.AddrOfPinnedObject();

                        InpProps.SetMediaType(ref mt);
                    }

                    finally

                    {
                        h.Free();
                    }

                    m_Writer.SetInputProps(0, InpProps);

                    if (MetadataAttributes != null)

                    {
                        WMHeaderInfo info = new WMHeaderInfo((IWMHeaderInfo)m_Writer);

                        foreach (WM_Attr attr in MetadataAttributes)

                        {
                            info.SetAttribute(attr);
                        }

                        info = null;
                    }

                    m_Writer.BeginWriting();

                    m_Profile = profile;
                }

                else

                {
                    throw new ArgumentException("Invalid profile", "profile");
                }
            }

            else

            {
                throw new ArgumentException("Invalid profile", "profile");
            }
        }
Exemplo n.º 17
0
 public Hv_bubbles_Context(double sampleRate, int poolKb=10) {
   gch = GCHandle.Alloc(msgQueue);
   _context = hv_bubbles_new_with_options(sampleRate, poolKb);
   hv_setPrintHook(_context, new PrintHook(OnPrint));
   hv_setUserData(_context, GCHandle.ToIntPtr(gch));
 }
Exemplo n.º 18
0
 internal ControlChangeNotify(Part parent)
 {
     _Parent   = parent;
     rcwHandle = GCHandle.Alloc(this, GCHandleType.Normal);
 }
Exemplo n.º 19
0
        /// <summary>
        /// Submit a log entry to the journal.
        /// </summary>
        public static unsafe LogResult Log(LogFlags flags, JournalMessage message)
        {
            Socket socket = GetJournalSocket();

            if (socket == null)
            {
                if (s_isSupported.Value)
                {
                    return(LogResult.NotAvailable);
                }
                else
                {
                    return(LogResult.NotSupported);
                }
            }

            if (message.IsEmpty)
            {
                return(LogResult.Success);
            }

            int priority = (int)flags & 0xf;

            if (priority != 0)
            {
                message.Append(JournalFieldName.Priority, priority - 1);
            }
            if (((flags & LogFlags.DontAppendSyslogIdentifier) == LogFlags.None) &&
                SyslogIdentifier != null)
            {
                message.Append(JournalFieldName.SyslogIdentifier, SyslogIdentifier);
            }

            List <ArraySegment <byte> > data = message.GetData();
            int dataLength = data.Count;

            if (dataLength > MaxIovs)
            {
                // We should handle this the same way as EMSGSIZE, which we don't handle atm.
                ErrorWhileLogging("size exceeded");
                return(LogResult.Size);
            }
            Span <IOVector> iovs    = stackalloc IOVector[dataLength];
            Span <GCHandle> handles = stackalloc GCHandle[dataLength];

            for (int i = 0; i < data.Count; i++)
            {
                handles[i]     = GCHandle.Alloc(data[i].Array, GCHandleType.Pinned);
                iovs[i].Base   = handles[i].AddrOfPinnedObject();
                iovs[i].Length = new IntPtr(data[i].Count);
            }
            int sendmsgFlags = 0;

            if ((flags & LogFlags.DropWhenBusy) != 0)
            {
                sendmsgFlags |= MSG_DONTWAIT;
            }
            LogResult result = LogResult.Success;

            fixed(IOVector *pIovs = &MemoryMarshal.GetReference(iovs))
            {
                bool loop;

                do
                {
                    loop = false;
                    msghdr msg;
                    msg.msg_iov    = pIovs;
                    msg.msg_iovlen = (SizeT)dataLength;
                    int rv = sendmsg(socket.Handle.ToInt32(), &msg, sendmsgFlags).ToInt32();
                    if (rv < 0)
                    {
                        int errno = Marshal.GetLastWin32Error();
                        if (errno == EINTR)
                        {
                            loop = true;
                        }
                        else if (errno == EAGAIN)
                        {
                            result = LogResult.Busy;
                        }
                        else
                        {
                            result = LogResult.UnknownError;
                            ErrorWhileLogging($"errno={errno}");
                        }
                    }
                } while (loop);
            }

            for (int i = 0; i < handles.Length; i++)
            {
                handles[i].Free();
            }
            return(result);
        }
Exemplo n.º 20
0
        private unsafe static int EncryptDecryptHelper(OP op, SSPIInterface secModule, SafeDeleteContext context, SecurityBuffer[] input, uint sequenceNumber)
        {
            Interop.SspiCli.SecurityBufferDescriptor sdcInOut = new Interop.SspiCli.SecurityBufferDescriptor(input.Length);
            var unmanagedBuffer = new Interop.SspiCli.SecurityBufferStruct[input.Length];

            fixed(Interop.SspiCli.SecurityBufferStruct *unmanagedBufferPtr = unmanagedBuffer)
            {
                sdcInOut.UnmanagedPointer = unmanagedBufferPtr;
                GCHandle[] pinnedBuffers = new GCHandle[input.Length];
                byte[][]   buffers       = new byte[input.Length][];
                try
                {
                    for (int i = 0; i < input.Length; i++)
                    {
                        SecurityBuffer iBuffer = input[i];
                        unmanagedBuffer[i].count = iBuffer.size;
                        unmanagedBuffer[i].type  = iBuffer.type;
                        if (iBuffer.token == null || iBuffer.token.Length == 0)
                        {
                            unmanagedBuffer[i].token = IntPtr.Zero;
                        }
                        else
                        {
                            pinnedBuffers[i]         = GCHandle.Alloc(iBuffer.token, GCHandleType.Pinned);
                            unmanagedBuffer[i].token = Marshal.UnsafeAddrOfPinnedArrayElement(iBuffer.token, iBuffer.offset);
                            buffers[i] = iBuffer.token;
                        }
                    }

                    // The result is written in the input Buffer passed as type=BufferType.Data.
                    int errorCode;
                    switch (op)
                    {
                    case OP.Encrypt:
                        errorCode = secModule.EncryptMessage(context, sdcInOut, sequenceNumber);
                        break;

                    case OP.Decrypt:
                        errorCode = secModule.DecryptMessage(context, sdcInOut, sequenceNumber);
                        break;

                    case OP.MakeSignature:
                        errorCode = secModule.MakeSignature(context, sdcInOut, sequenceNumber);
                        break;

                    case OP.VerifySignature:
                        errorCode = secModule.VerifySignature(context, sdcInOut, sequenceNumber);
                        break;

                    default:
                        if (GlobalLog.IsEnabled)
                        {
                            GlobalLog.Assert("SSPIWrapper::EncryptDecryptHelper", "Unknown OP: " + op);
                        }

                        Debug.Fail("SSPIWrapper::EncryptDecryptHelper", "Unknown OP: " + op);
                        throw NotImplemented.ByDesignWithMessage(SR.net_MethodNotImplementedException);
                    }

                    // Marshalling back returned sizes / data.
                    for (int i = 0; i < input.Length; i++)
                    {
                        SecurityBuffer iBuffer = input[i];
                        iBuffer.size = unmanagedBuffer[i].count;
                        iBuffer.type = unmanagedBuffer[i].type;

                        if (iBuffer.size == 0)
                        {
                            iBuffer.offset = 0;
                            iBuffer.token  = null;
                        }
                        else
                        {
                            checked
                            {
                                // Find the buffer this is inside of.  Usually they all point inside buffer 0.
                                int j;
                                for (j = 0; j < input.Length; j++)
                                {
                                    if (buffers[j] == null)
                                    {
                                        continue;
                                    }

                                    byte *bufferAddress = (byte *)Marshal.UnsafeAddrOfPinnedArrayElement(buffers[j], 0);
                                    if ((byte *)unmanagedBuffer[i].token >= bufferAddress &&
                                        (byte *)unmanagedBuffer[i].token + iBuffer.size <= bufferAddress + buffers[j].Length)
                                    {
                                        iBuffer.offset = (int)((byte *)unmanagedBuffer[i].token - bufferAddress);
                                        iBuffer.token  = buffers[j];
                                        break;
                                    }
                                }

                                if (j >= input.Length)
                                {
                                    if (GlobalLog.IsEnabled)
                                    {
                                        GlobalLog.Assert("SSPIWrapper::EncryptDecryptHelper", "Output buffer out of range.");
                                    }

                                    Debug.Fail("SSPIWrapper::EncryptDecryptHelper", "Output buffer out of range.");
                                    iBuffer.size   = 0;
                                    iBuffer.offset = 0;
                                    iBuffer.token  = null;
                                }
                            }
                        }

                        // Backup validate the new sizes.
                        if (iBuffer.offset < 0 || iBuffer.offset > (iBuffer.token == null ? 0 : iBuffer.token.Length))
                        {
                            if (GlobalLog.IsEnabled)
                            {
                                GlobalLog.AssertFormat("SSPIWrapper::EncryptDecryptHelper|'offset' out of range.  [{0}]", iBuffer.offset);
                            }

                            Debug.Fail("SSPIWrapper::EncryptDecryptHelper|'offset' out of range.  [" + iBuffer.offset + "]");
                        }

                        if (iBuffer.size < 0 || iBuffer.size > (iBuffer.token == null ? 0 : iBuffer.token.Length - iBuffer.offset))
                        {
                            if (GlobalLog.IsEnabled)
                            {
                                GlobalLog.AssertFormat("SSPIWrapper::EncryptDecryptHelper|'size' out of range.  [{0}]", iBuffer.size);
                            }

                            Debug.Fail("SSPIWrapper::EncryptDecryptHelper|'size' out of range.  [" + iBuffer.size + "]");
                        }
                    }

                    if (errorCode != 0 && NetEventSource.Log.IsEnabled())
                    {
                        if (errorCode == Interop.SspiCli.SEC_I_RENEGOTIATE)
                        {
                            NetEventSource.PrintError(NetEventSource.ComponentType.Security, SR.Format(SR.event_OperationReturnedSomething, op, "SEC_I_RENEGOTIATE"));
                        }
                        else
                        {
                            NetEventSource.PrintError(NetEventSource.ComponentType.Security, SR.Format(SR.net_log_operation_failed_with_error, op, String.Format(CultureInfo.CurrentCulture, "0X{0:X}", errorCode)));
                        }
                    }

                    return(errorCode);
                }
                finally
                {
                    for (int i = 0; i < pinnedBuffers.Length; ++i)
                    {
                        if (pinnedBuffers[i].IsAllocated)
                        {
                            pinnedBuffers[i].Free();
                        }
                    }
                }
            }
        }
Exemplo n.º 21
0
        internal static unsafe byte[] DownloadAsset(string uri, ref TimeSpan remainingDownloadTime)
        {
            if (remainingDownloadTime <= TimeSpan.Zero)
            {
                return(null);
            }

            List <byte[]> dataPieces = new List <byte[]>();

            using (Interop.libcurl.SafeCurlHandle curlHandle = Interop.libcurl.curl_easy_init())
            {
                GCHandle gcHandle = GCHandle.Alloc(dataPieces);

                try
                {
                    IntPtr dataHandlePtr = GCHandle.ToIntPtr(gcHandle);
                    Interop.libcurl.curl_easy_setopt(curlHandle, Interop.libcurl.CURLoption.CURLOPT_URL, uri);
                    Interop.libcurl.curl_easy_setopt(curlHandle, Interop.libcurl.CURLoption.CURLOPT_WRITEDATA, dataHandlePtr);
                    Interop.libcurl.curl_easy_setopt(curlHandle, Interop.libcurl.CURLoption.CURLOPT_WRITEFUNCTION, s_writeCallback);
                    Interop.libcurl.curl_easy_setopt(curlHandle, Interop.libcurl.CURLoption.CURLOPT_FOLLOWLOCATION, 1L);

                    Stopwatch stopwatch = Stopwatch.StartNew();
                    int       res       = Interop.libcurl.curl_easy_perform(curlHandle);
                    stopwatch.Stop();

                    // TimeSpan.Zero isn't a worrisome value on the subtraction, it only
                    // means "no limit" on the original input.
                    remainingDownloadTime -= stopwatch.Elapsed;

                    if (res != Interop.libcurl.CURLcode.CURLE_OK)
                    {
                        return(null);
                    }
                }
                finally
                {
                    gcHandle.Free();
                }
            }

            if (dataPieces.Count == 0)
            {
                return(null);
            }

            if (dataPieces.Count == 1)
            {
                return(dataPieces[0]);
            }

            int dataLen = 0;

            for (int i = 0; i < dataPieces.Count; i++)
            {
                dataLen += dataPieces[i].Length;
            }

            byte[] data   = new byte[dataLen];
            int    offset = 0;

            for (int i = 0; i < dataPieces.Count; i++)
            {
                byte[] piece = dataPieces[i];

                Buffer.BlockCopy(piece, 0, data, offset, piece.Length);
                offset += piece.Length;
            }

            return(data);
        }
Exemplo n.º 22
0
        // Convert the raw data in the frame's buffer into the bitmap's data. This method doesn't support
        // the following Pixel formats: eFmtRgb48, eFmtYuv411 and eFmtYuv444.
        static unsafe bool Frame2Data(ref BitmapData Data)
        {
            switch (GCamera.Frame.Format)
            {
            case tImageFormat.eFmtMono8:
            {
                UInt32 lOffset = 0;
                UInt32 lPos    = 0;
                byte * lDst    = (byte *)Data.Scan0;

                while (lOffset < GCamera.Frame.ImageBufferSize)
                {
                    lDst[lPos]     = GCamera.Buffer[lOffset];
                    lDst[lPos + 1] = GCamera.Buffer[lOffset];
                    lDst[lPos + 2] = GCamera.Buffer[lOffset];

                    lOffset++;
                    lPos += 3;

                    // Take care of the padding in the destination bitmap.
                    if ((lOffset % GCamera.Frame.Width) == 0)
                    {
                        lPos += (UInt32)Data.Stride - (GCamera.Frame.Width * 3);
                    }
                }

                return(true);
            }

            case tImageFormat.eFmtMono16:
            {
                UInt32  lOffset  = 0;
                UInt32  lPos     = 0;
                byte *  lDst     = (byte *)Data.Scan0;
                byte    bitshift = (byte)((int)GCamera.Frame.BitDepth - 8);
                UInt16 *lSrc     = (UInt16 *)GCamera.Frame.ImageBuffer;

                while (lOffset < GCamera.Frame.Width * GCamera.Frame.Height)
                {
                    lDst[lPos]     = (byte)(lSrc[lOffset] >> bitshift);
                    lDst[lPos + 1] = lDst[lPos];
                    lDst[lPos + 2] = lDst[lPos];

                    lOffset++;
                    lPos += 3;

                    // Take care of the padding in the destination bitmap.
                    if ((lOffset % GCamera.Frame.Width) == 0)
                    {
                        lPos += (UInt32)Data.Stride - (GCamera.Frame.Width * 3);
                    }
                }

                return(true);
            }

            case tImageFormat.eFmtBayer8:
            {
                UInt32   WidthSize = GCamera.Frame.Width * 3;
                GCHandle pFrame    = GCHandle.Alloc(GCamera.Frame, GCHandleType.Pinned);
                UInt32   remainder = (((WidthSize + 3U) & ~3U) - WidthSize);

                // Interpolate the colors.
                IntPtr pRed   = (IntPtr)((byte *)Data.Scan0 + 2);
                IntPtr pGreen = (IntPtr)((byte *)Data.Scan0 + 1);
                IntPtr pBlue  = (IntPtr)((byte *)Data.Scan0);
                Pv.ColorInterpolate(pFrame.AddrOfPinnedObject(), pRed, pGreen, pBlue, 2, remainder);

                pFrame.Free();

                return(true);
            }

            case tImageFormat.eFmtBayer16:
            {
                UInt32   WidthSize = GCamera.Frame.Width * 3;
                UInt32   lOffset   = 0;
                byte     bitshift  = (byte)((int)GCamera.Frame.BitDepth - 8);
                UInt16 * lSrc      = (UInt16 *)GCamera.Frame.ImageBuffer;
                byte *   lDst      = (byte *)GCamera.Frame.ImageBuffer;
                UInt32   remainder = (((WidthSize + 3U) & ~3U) - WidthSize);
                GCHandle pFrame;

                GCamera.Frame.Format = tImageFormat.eFmtBayer8;

                pFrame = GCHandle.Alloc(GCamera.Frame, GCHandleType.Pinned);

                // Shift the pixel.
                while (lOffset < GCamera.Frame.Width * GCamera.Frame.Height)
                {
                    lDst[lOffset] = (byte)(lSrc[lOffset++] >> bitshift);
                }

                // Interpolate the colors.
                IntPtr pRed   = (IntPtr)((byte *)Data.Scan0 + 2);
                IntPtr pGreen = (IntPtr)((byte *)Data.Scan0 + 1);
                IntPtr pBlue  = (IntPtr)((byte *)Data.Scan0);
                Pv.ColorInterpolate(pFrame.AddrOfPinnedObject(), pRed, pGreen, pBlue, 2, remainder);

                pFrame.Free();

                return(true);
            }

            case tImageFormat.eFmtRgb24:
            {
                UInt32 lOffset = 0;
                UInt32 lPos    = 0;
                byte * lDst    = (byte *)Data.Scan0;

                while (lOffset < GCamera.Frame.ImageBufferSize)
                {
                    // Copy the data.
                    lDst[lPos]     = GCamera.Buffer[lOffset + 2];
                    lDst[lPos + 1] = GCamera.Buffer[lOffset + 1];
                    lDst[lPos + 2] = GCamera.Buffer[lOffset];

                    lOffset += 3;
                    lPos    += 3;

                    // Take care of the padding in the destination bitmap.
                    if ((lOffset % (GCamera.Frame.Width * 3)) == 0)
                    {
                        lPos += (UInt32)Data.Stride - (GCamera.Frame.Width * 3);
                    }
                }

                return(true);
            }

            case tImageFormat.eFmtRgb48:
            {
                UInt32  lOffset  = 0;
                UInt32  lPos     = 0;
                UInt32  lLength  = GCamera.Frame.ImageBufferSize / sizeof(UInt16);
                UInt16 *lSrc     = (UInt16 *)GCamera.Frame.ImageBuffer;
                byte *  lDst     = (byte *)Data.Scan0;
                byte    bitshift = (byte)((int)GCamera.Frame.BitDepth - 8);

                while (lOffset < lLength)
                {
                    // Copy the data.
                    lDst[lPos]     = (byte)(lSrc[lOffset + 2] >> bitshift);
                    lDst[lPos + 1] = (byte)(lSrc[lOffset + 1] >> bitshift);
                    lDst[lPos + 2] = (byte)(lSrc[lOffset] >> bitshift);

                    lOffset += 3;
                    lPos    += 3;

                    // Take care of the padding in the destination bitmap.
                    if ((lOffset % (GCamera.Frame.Width * 3)) == 0)
                    {
                        lPos += (UInt32)Data.Stride - (GCamera.Frame.Width * 3);
                    }
                }

                return(true);
            }

            case tImageFormat.eFmtYuv411:
            {
                UInt32 lOffset = 0;
                UInt32 lPos = 0;
                byte * lDst = (byte *)Data.Scan0;
                int    y1, y2, y3, y4, u, v;
                int    r, g, b;

                r = g = b = 0;

                while (lOffset < GCamera.Frame.ImageBufferSize)
                {
                    u  = GCamera.Buffer[lOffset++];
                    y1 = GCamera.Buffer[lOffset++];
                    y2 = GCamera.Buffer[lOffset++];
                    v  = GCamera.Buffer[lOffset++];
                    y3 = GCamera.Buffer[lOffset++];
                    y4 = GCamera.Buffer[lOffset++];

                    YUV2RGB(y1, u, v, ref r, ref g, ref b);
                    lDst[lPos++] = (byte)b;
                    lDst[lPos++] = (byte)g;
                    lDst[lPos++] = (byte)r;
                    YUV2RGB(y2, u, v, ref r, ref g, ref b);
                    lDst[lPos++] = (byte)b;
                    lDst[lPos++] = (byte)g;
                    lDst[lPos++] = (byte)r;
                    YUV2RGB(y3, u, v, ref r, ref g, ref b);
                    lDst[lPos++] = (byte)b;
                    lDst[lPos++] = (byte)g;
                    lDst[lPos++] = (byte)r;
                    YUV2RGB(y4, u, v, ref r, ref g, ref b);
                    lDst[lPos++] = (byte)b;
                    lDst[lPos++] = (byte)g;
                    lDst[lPos++] = (byte)r;
                }

                return(true);
            }

            case tImageFormat.eFmtYuv422:
            {
                UInt32 lOffset = 0;
                UInt32 lPos = 0;
                byte * lDst = (byte *)Data.Scan0;
                int    y1, y2, u, v;
                int    r, g, b;

                r = g = b = 0;

                while (lOffset < GCamera.Frame.ImageBufferSize)
                {
                    u  = GCamera.Buffer[lOffset++];
                    y1 = GCamera.Buffer[lOffset++];
                    v  = GCamera.Buffer[lOffset++];
                    y2 = GCamera.Buffer[lOffset++];

                    YUV2RGB(y1, u, v, ref r, ref g, ref b);
                    lDst[lPos++] = (byte)b;
                    lDst[lPos++] = (byte)g;
                    lDst[lPos++] = (byte)r;
                    YUV2RGB(y2, u, v, ref r, ref g, ref b);
                    lDst[lPos++] = (byte)b;
                    lDst[lPos++] = (byte)g;
                    lDst[lPos++] = (byte)r;
                }

                return(true);
            }

            case tImageFormat.eFmtYuv444:
            {
                UInt32 lOffset = 0;
                UInt32 lPos = 0;
                byte * lDst = (byte *)Data.Scan0;
                int    y1, y2, u, v;
                int    r, g, b;

                r = g = b = 0;

                while (lOffset < GCamera.Frame.ImageBufferSize)
                {
                    u  = GCamera.Buffer[lOffset++];
                    y1 = GCamera.Buffer[lOffset++];
                    v  = GCamera.Buffer[lOffset++];
                    lOffset++;
                    y2 = GCamera.Buffer[lOffset++];
                    lOffset++;

                    YUV2RGB(y1, u, v, ref r, ref g, ref b);
                    lDst[lPos++] = (byte)b;
                    lDst[lPos++] = (byte)g;
                    lDst[lPos++] = (byte)r;
                    YUV2RGB(y2, u, v, ref r, ref g, ref b);
                    lDst[lPos++] = (byte)b;
                    lDst[lPos++] = (byte)g;
                    lDst[lPos++] = (byte)r;
                }

                return(true);
            }

            default:
                return(false);
            }
        }
Exemplo n.º 23
0
        public static IntPtr Pin(UInt32 size, eLeapAllocatorType typeHint, IntPtr state)
        {
            try
            {
                //Construct a key to identify the desired allocation
                PoolKey key = new PoolKey()
                {
                    type = typeHint,
                    size = size
                };

                //Attempt to find the pool that holds this type of allocation
                Queue <object> pool;
                if (!_pooledMemory.TryGetValue(key, out pool))
                {
                    //Construct a new pool if none exists yet
                    pool = new Queue <object>();
                    _pooledMemory[key] = pool;
                }

                //Attempt to get an object from the pool
                object memory;
                if (EnablePooling && pool.Count > MinPoolSize)
                {
                    memory = pool.Dequeue();
                }
                else
                {
                    //If the pool is empty, we need to construct a new object
                    switch (typeHint)
                    {
                    default:
                    case eLeapAllocatorType.eLeapAllocatorType_Uint8:
                        memory = new byte[size];
                        break;

                    case eLeapAllocatorType.eLeapAllocatorType_Float:
                        memory = new float[(size + sizeof(float) - 1) / sizeof(float)];
                        break;
                    }
                }

                //Pin the object so its address will not change
                GCHandle handle = GCHandle.Alloc(memory, GCHandleType.Pinned);
                IntPtr   ptr    = handle.AddrOfPinnedObject();

                //Put the information about the newly pinned allocation into the
                //active memory map so it can be retrieved and freed layer.
                _activeMemory.TryAdd(ptr, new ActiveMemoryInfo()
                {
                    handle = handle,
                    key    = key
                });

                return(ptr);
            }
            catch (Exception e)
            {
                UnityEngine.Debug.LogException(e);
            }

            return(IntPtr.Zero);
        }
 public InputStream(SoundIO.Device device)
 {
     _self   = GCHandle.Alloc(this);
     _device = device;
     OpenStream();
 }
Exemplo n.º 25
0
        /// <summary>Actually sends the data to mIRC.</summary>
        private Task <string> dispatchMessageAsync(uint message, string command, short eventID, CancellationToken token)
        {
            var taskSource = new TaskCompletionSource <string>();
            var buffer     = new byte[FileSize];

            prepareMappedFile(message, command, buffer);

            // Send the command to mIRC.
            currentDelegate = this.commandCallback;
            SendMessageCallbackW(this.targetWindow, message, new IntPtr(24 | eventID << 16), this.fileNumber, currentDelegate, (IntPtr)GCHandle.Alloc(taskSource));
            token.Register(() => this.cancelled(taskSource));

            return(taskSource.Task);
        }
Exemplo n.º 26
0
        /// Starts a service in the machine specified.
        public void Start(string[] args)
        {
            if (args == null)
            {
                throw new ArgumentNullException("args");
            }

            IntPtr serviceHandle = GetServiceHandle(Interop.mincore.ServiceOptions.SERVICE_START);

            try
            {
                IntPtr[] argPtrs = new IntPtr[args.Length];
                int      i       = 0;
                try
                {
                    for (i = 0; i < args.Length; i++)
                    {
                        if (args[i] == null)
                        {
                            throw new ArgumentNullException(SR.ArgsCantBeNull, "args");
                        }

                        argPtrs[i] = Marshal.StringToHGlobalUni(args[i]);
                    }
                }
                catch
                {
                    for (int j = 0; j < i; j++)
                    {
                        Marshal.FreeHGlobal(argPtrs[i]);
                    }
                    throw;
                }

                GCHandle argPtrsHandle = new GCHandle();
                try
                {
                    argPtrsHandle = GCHandle.Alloc(argPtrs, GCHandleType.Pinned);
                    bool result = Interop.mincore.StartService(serviceHandle, args.Length, (IntPtr)argPtrsHandle.AddrOfPinnedObject());
                    if (!result)
                    {
                        Exception inner = new Win32Exception(Marshal.GetLastWin32Error());
                        throw new InvalidOperationException(SR.Format(SR.CannotStart, ServiceName, _machineName), inner);
                    }
                }
                finally
                {
                    for (i = 0; i < args.Length; i++)
                    {
                        Marshal.FreeHGlobal(argPtrs[i]);
                    }
                    if (argPtrsHandle.IsAllocated)
                    {
                        argPtrsHandle.Free();
                    }
                }
            }
            finally
            {
                Interop.mincore.CloseServiceHandle(serviceHandle);
            }
        }
Exemplo n.º 27
0
        // This essentially wraps SSL* SSL_new()
        internal static SafeSslHandle AllocateSslHandle(SafeFreeSslCredentials credential, SslAuthenticationOptions sslAuthenticationOptions)
        {
            SafeSslHandle?       sslHandle    = null;
            SafeSslContextHandle?sslCtxHandle = null;
            SafeSslContextHandle?newCtxHandle = null;
            SslProtocols         protocols    = CalculateEffectiveProtocols(sslAuthenticationOptions);
            bool hasAlpn         = sslAuthenticationOptions.ApplicationProtocols != null && sslAuthenticationOptions.ApplicationProtocols.Count != 0;
            bool cacheSslContext = !DisableTlsResume && sslAuthenticationOptions.EncryptionPolicy == EncryptionPolicy.RequireEncryption && sslAuthenticationOptions.CipherSuitesPolicy == null;

            if (cacheSslContext)
            {
                if (sslAuthenticationOptions.IsClient)
                {
                    // We don't support client resume on old OpenSSL versions.
                    // We don't want to try on empty TargetName since that is our key.
                    // And we don't want to mess up with client authentication. It may be possible
                    // but it seems safe to get full new session.
                    if (!Interop.Ssl.Capabilities.Tls13Supported ||
                        string.IsNullOrEmpty(sslAuthenticationOptions.TargetHost) ||
                        sslAuthenticationOptions.CertificateContext != null ||
                        sslAuthenticationOptions.CertSelectionDelegate != null)
                    {
                        cacheSslContext = false;
                    }
                }
                else
                {
                    // Server should always have certificate
                    Debug.Assert(sslAuthenticationOptions.CertificateContext != null);
                    if (sslAuthenticationOptions.CertificateContext == null ||
                        sslAuthenticationOptions.CertificateContext.SslContexts == null)
                    {
                        cacheSslContext = false;
                    }
                }
            }

            if (cacheSslContext)
            {
                if (sslAuthenticationOptions.IsServer)
                {
                    sslAuthenticationOptions.CertificateContext !.SslContexts !.TryGetValue(protocols | (hasAlpn ? FakeAlpnSslProtocol : SslProtocols.None), out sslCtxHandle);
                }
                else
                {
                    s_clientSslContexts.TryGetValue(protocols, out sslCtxHandle);
                }
            }

            if (sslCtxHandle == null)
            {
                // We did not get SslContext from cache
                sslCtxHandle = newCtxHandle = AllocateSslContext(credential, sslAuthenticationOptions, protocols, cacheSslContext);

                if (cacheSslContext)
                {
                    bool added = sslAuthenticationOptions.IsServer ?
                                 sslAuthenticationOptions.CertificateContext !.SslContexts !.TryAdd(protocols | (SslProtocols)(hasAlpn ? 1 : 0), newCtxHandle) :
                                 s_clientSslContexts.TryAdd(protocols, newCtxHandle);
                    if (added)
                    {
                        newCtxHandle = null;
                    }
                }
            }

            GCHandle alpnHandle = default;

            try
            {
                sslHandle = SafeSslHandle.Create(sslCtxHandle, sslAuthenticationOptions.IsServer);
                Debug.Assert(sslHandle != null, "Expected non-null return value from SafeSslHandle.Create");
                if (sslHandle.IsInvalid)
                {
                    sslHandle.Dispose();
                    throw CreateSslException(SR.net_allocate_ssl_context_failed);
                }

                if (sslAuthenticationOptions.ApplicationProtocols != null && sslAuthenticationOptions.ApplicationProtocols.Count != 0)
                {
                    if (sslAuthenticationOptions.IsServer)
                    {
                        Debug.Assert(Interop.Ssl.SslGetData(sslHandle) == IntPtr.Zero);
                        alpnHandle = GCHandle.Alloc(sslAuthenticationOptions.ApplicationProtocols);
                        Interop.Ssl.SslSetData(sslHandle, GCHandle.ToIntPtr(alpnHandle));
                        sslHandle.AlpnHandle = alpnHandle;
                    }
                    else
                    {
                        if (Interop.Ssl.SslSetAlpnProtos(sslHandle, sslAuthenticationOptions.ApplicationProtocols) != 0)
                        {
                            throw CreateSslException(SR.net_alpn_config_failed);
                        }
                    }
                }

                if (sslAuthenticationOptions.IsClient)
                {
                    // The IdnMapping converts unicode input into the IDNA punycode sequence.
                    string punyCode = string.IsNullOrEmpty(sslAuthenticationOptions.TargetHost) ? string.Empty : s_idnMapping.GetAscii(sslAuthenticationOptions.TargetHost !);

                    // Similar to windows behavior, set SNI on openssl by default for client context, ignore errors.
                    if (!Ssl.SslSetTlsExtHostName(sslHandle, punyCode))
                    {
                        Crypto.ErrClearError();
                    }

                    if (cacheSslContext && !string.IsNullOrEmpty(punyCode))
                    {
                        sslCtxHandle.TrySetSession(sslHandle, punyCode);
                    }

                    // relevant to TLS 1.3 only: if user supplied a client cert or cert callback,
                    // advertise that we are willing to send the certificate post-handshake.
                    if (sslAuthenticationOptions.ClientCertificates?.Count > 0 ||
                        sslAuthenticationOptions.CertSelectionDelegate != null)
                    {
                        Ssl.SslSetPostHandshakeAuth(sslHandle, 1);
                    }

                    // Set client cert callback, this will interrupt the handshake with SecurityStatusPalErrorCode.CredentialsNeeded
                    // if server actually requests a certificate.
                    Ssl.SslSetClientCertCallback(sslHandle, 1);
                }
                else // sslAuthenticationOptions.IsServer
                {
                    if (sslAuthenticationOptions.RemoteCertRequired)
                    {
                        Ssl.SslSetVerifyPeer(sslHandle);
                    }

                    if (sslAuthenticationOptions.CertificateContext?.Trust?._sendTrustInHandshake == true)
                    {
                        SslCertificateTrust        trust    = sslAuthenticationOptions.CertificateContext !.Trust !;
                        X509Certificate2Collection certList = (trust._trustList ?? trust._store !.Certificates);

                        Debug.Assert(certList != null, "certList != null");
                        Span <IntPtr> handles = certList.Count <= 256
                            ? stackalloc IntPtr[256]
                            : new IntPtr[certList.Count];

                        for (int i = 0; i < certList.Count; i++)
                        {
                            handles[i] = certList[i].Handle;
                        }

                        if (!Ssl.SslAddClientCAs(sslHandle, handles.Slice(0, certList.Count)))
                        {
                            // The method can fail only when the number of cert names exceeds the maximum capacity
                            // supported by STACK_OF(X509_NAME) structure, which should not happen under normal
                            // operation.
                            Debug.Fail("Failed to add issuer to trusted CA list.");
                        }
                    }
                }
            }
            catch
            {
                if (alpnHandle.IsAllocated)
                {
                    alpnHandle.Free();
                }

                throw;
            }
            finally
            {
                newCtxHandle?.Dispose();
            }

            return(sslHandle);
        }
Exemplo n.º 28
0
Arquivo: Value.cs Projeto: ynkbt/moon
        //
        // How do we support "null" values, should the caller take care of that?
        //
        // The caller is responsible for calling value_free_value on the returned Value
        public static Value FromObject(object v, bool box_value_types)
        {
            Value value = new Value();

            unsafe {
                if (box_value_types && (v is ValueType || v is string))
                {
                    value.boxed_valuetype = GCHandle.Alloc(v);
                }

                if (v is IEasingFunction && !(v is EasingFunctionBase))
                {
                    v = new EasingFunctionWrapper(v as IEasingFunction);
                }

                if (v is INativeEventObjectWrapper)
                {
                    INativeEventObjectWrapper dov = (INativeEventObjectWrapper)v;

                    if (dov.NativeHandle == IntPtr.Zero)
                    {
                        throw new Exception(String.Format(
                                                "Object {0} has not set its native property", dov.GetType()));
                    }

                    NativeMethods.event_object_ref(dov.NativeHandle);

                    value.Kind = dov.GetKind();
                    value.u.p  = dov.NativeHandle;
                }
                else if (v is DependencyProperty)
                {
                    value.Kind = Kind.DEPENDENCYPROPERTY;
                    value.u.p  = ((DependencyProperty)v).Native;
                }
                else if (v is int || (v.GetType().IsEnum&& Enum.GetUnderlyingType(v.GetType()) == typeof(int)))
                {
                    value.Kind  = Deployment.Current.Types.TypeToKind(v.GetType());
                    value.u.i32 = (int)v;
                }
                else if (v is byte || (v.GetType().IsEnum&& Enum.GetUnderlyingType(v.GetType()) == typeof(byte)))
                {
                    value.Kind  = Deployment.Current.Types.TypeToKind(v.GetType());
                    value.u.i32 = (byte)v;
                }
                else if (v is bool)
                {
                    value.Kind  = Kind.BOOL;
                    value.u.i32 = ((bool)v) ? 1 : 0;
                }
                else if (v is double)
                {
                    value.Kind = Kind.DOUBLE;
                    value.u.d  = (double)v;
                }
                else if (v is float)
                {
                    value.Kind = Kind.FLOAT;
                    value.u.f  = (float)v;
                }
                else if (v is long)
                {
                    value.Kind  = Kind.INT64;
                    value.u.i64 = (long)v;
                }
                else if (v is TimeSpan)
                {
                    TimeSpan ts = (TimeSpan)v;
                    value.Kind  = Kind.TIMESPAN;
                    value.u.i64 = ts.Ticks;
                }
                else if (v is ulong)
                {
                    value.Kind   = Kind.UINT64;
                    value.u.ui64 = (ulong)v;
                }
                else if (v is uint)
                {
                    value.Kind   = Kind.UINT32;
                    value.u.ui32 = (uint)v;
                }
                else if (v is char)
                {
                    value.Kind   = Kind.CHAR;
                    value.u.ui32 = (uint)(char)v;
                }
                else if (v is string)
                {
                    value.Kind = Kind.STRING;

                    value.u.p = StringToIntPtr((string)v);
                }
                else if (v is Rect)
                {
                    Rect rect = (Rect)v;
                    value.Kind = Kind.RECT;
                    value.u.p  = Marshal.AllocHGlobal(sizeof(Rect));
                    Marshal.StructureToPtr(rect, value.u.p, false);                      // Unmanaged and managed structure layout is equal.
                }
                else if (v is Size)
                {
                    Size size = (Size)v;
                    value.Kind = Kind.SIZE;
                    value.u.p  = Marshal.AllocHGlobal(sizeof(Size));
                    Marshal.StructureToPtr(size, value.u.p, false);                      // Unmanaged and managed structure layout is equal.
                }
                else if (v is CornerRadius)
                {
                    CornerRadius corner = (CornerRadius)v;
                    value.Kind = Kind.CORNERRADIUS;
                    value.u.p  = Marshal.AllocHGlobal(sizeof(CornerRadius));
                    Marshal.StructureToPtr(corner, value.u.p, false);                      // Unmanaged and managed structure layout is equal.
                }
                else if (v is AudioFormat)
                {
                    AudioFormat f = (AudioFormat)v;
                    value.Kind = Kind.AUDIOFORMAT;
                    value.u.p  = Marshal.AllocHGlobal(sizeof(UnmanagedAudioFormat));
                    UnmanagedAudioFormat *format = (UnmanagedAudioFormat *)value.u.p;
                    format->bitsPerSample    = f.BitsPerSample;
                    format->channels         = f.Channels;
                    format->samplesPerSecond = f.SamplesPerSecond;
                    format->waveFormat       = f.WaveFormat;
                }
                else if (v is VideoFormat)
                {
                    VideoFormat f = (VideoFormat)v;
                    value.Kind = Kind.VIDEOFORMAT;
                    value.u.p  = Marshal.AllocHGlobal(sizeof(UnmanagedVideoFormat));
                    UnmanagedVideoFormat *format = (UnmanagedVideoFormat *)value.u.p;
                    format->framesPerSecond = f.FramesPerSecond;
                    format->height          = f.PixelHeight;
                    format->width           = f.PixelWidth;
                    format->stride          = f.Stride;
                    format->pixelFormat     = f.PixelFormat;
                }
                else if (v is Point)
                {
                    Point pnt = (Point)v;
                    value.Kind = Kind.POINT;
                    value.u.p  = Marshal.AllocHGlobal(sizeof(Point));
                    Marshal.StructureToPtr(pnt, value.u.p, false);                      // Unmanaged and managed structure layout is equal.
                }
                else if (v is Thickness)
                {
                    Thickness thickness = (Thickness)v;
                    value.Kind = Kind.THICKNESS;
                    value.u.p  = Marshal.AllocHGlobal(sizeof(Thickness));
                    Marshal.StructureToPtr(thickness, value.u.p, false);                      // Unmanaged and managed structure layout is equal.
                }
                else if (v is Color)
                {
                    Color c = (Color)v;
                    value.Kind = Kind.COLOR;
                    value.u.p  = Marshal.AllocHGlobal(sizeof(UnmanagedColor));
                    UnmanagedColor *color = (UnmanagedColor *)value.u.p;
                    color->r = c.R / 255.0f;
                    color->g = c.G / 255.0f;
                    color->b = c.B / 255.0f;
                    color->a = c.A / 255.0f;
                }
                else if (v is Matrix)
                {
                    // hack around the fact that managed Matrix is a struct while unmanaged Matrix is a DO
                    // i.e. the unmanaged and managed structure layouts ARE NOT equal
                    return(FromObject(new UnmanagedMatrix((Matrix)v), box_value_types));
                }
                else if (v is StylusPoint)
                {
                    return(FromObject(new UnmanagedStylusPoint((StylusPoint)v), box_value_types));
                }
                else if (v is Matrix3D)
                {
                    // hack around the fact that managed Matrix3D is a struct while unmanaged Matrix3D is a DO
                    // i.e. the unmanaged and managed structure layouts ARE NOT equal
                    return(FromObject(new UnmanagedMatrix3D((Matrix3D)v), box_value_types));
                }
                else if (v is Duration)
                {
                    Duration d = (Duration)v;
                    value.Kind = Kind.DURATION;
                    value.u.p  = Marshal.AllocHGlobal(sizeof(Duration));
                    Marshal.StructureToPtr(d, value.u.p, false);                      // Unmanaged and managed structure layout is equal.
                }
                else if (v is KeyTime)
                {
                    KeyTime k = (KeyTime)v;
                    value.Kind = Kind.KEYTIME;
                    value.u.p  = Marshal.AllocHGlobal(sizeof(KeyTime));
                    Marshal.StructureToPtr(k, value.u.p, false);                      // Unmanaged and managed structure layout is equal.
                }
                else if (v is RepeatBehavior)
                {
                    RepeatBehavior d = (RepeatBehavior)v;
                    value.Kind = Kind.REPEATBEHAVIOR;
                    value.u.p  = Marshal.AllocHGlobal(sizeof(RepeatBehavior));
                    Marshal.StructureToPtr(d, value.u.p, false);                      // Unmanaged and managed structure layout is equal.
                }
                else if (v is FontFamily)
                {
                    FontFamily family = (FontFamily)v;
                    value.Kind = Kind.FONTFAMILY;
                    value.u.p  = Marshal.AllocHGlobal(sizeof(UnmanagedFontFamily));
                    Marshal.StructureToPtr(family, value.u.p, false);                      // Unmanaged and managed structure layout is equal.
                }

                else if (v is FontSource)
                {
                    FontSource source = (FontSource)v;

                    value.Kind = Kind.FONTSOURCE;

                    if (source.wrapper != null || source.typeface != null)
                    {
                        value.u.p = Marshal.AllocHGlobal(sizeof(UnmanagedFontSource));
                        UnmanagedFontSource *ufs = (UnmanagedFontSource *)value.u.p;
                        ufs->type = source.type;

                        switch (source.type)
                        {
                        case FontSourceType.ManagedStream:
                            ManagedStreamCallbacks callbacks = source.wrapper.GetCallbacks();
                            ufs->source.stream = Marshal.AllocHGlobal(sizeof(UnmanagedStreamCallbacks));
                            Marshal.StructureToPtr(callbacks, ufs->source.stream, false);
                            break;

                        case FontSourceType.GlyphTypeface:
                            ufs->source.typeface = source.typeface.Native;
                            break;
                        }
                    }
                    else
                    {
                        value.IsNull = true;
                    }
                }

                else if (v is PropertyPath)
                {
                    PropertyPath propertypath = (PropertyPath)v;
                    value.Kind = Kind.PROPERTYPATH;
                    value.u.p  = Marshal.AllocHGlobal(sizeof(UnmanagedPropertyPath));

                    UnmanagedPropertyPath *upp = (UnmanagedPropertyPath *)value.u.p;
                    upp->property = propertypath.NativeDP;
                    if (upp->property == IntPtr.Zero)
                    {
                        upp->pathString         = StringToIntPtr(propertypath.Path);
                        upp->expandedPathString = StringToIntPtr(propertypath.ExpandedPath);
                    }
                    else
                    {
                        upp->pathString         = IntPtr.Zero;
                        upp->expandedPathString = IntPtr.Zero;
                    }
                }
                else if (v is Uri)
                {
                    Uri uri = (Uri)v;

                    value.Kind = Kind.URI;
                    value.u.p  = UriHelper.ToNativeUri(uri);
                }
                else if (v is XmlLanguage)
                {
                    XmlLanguage lang = (XmlLanguage)v;

                    value.Kind = Kind.XMLLANGUAGE;
                    value.u.p  = StringToIntPtr(lang.IetfLanguageTag);
                }
                else if (v is Cursor)
                {
                    Cursor c = (Cursor)v;

                    value.Kind  = Kind.CURSORTYPE;
                    value.u.i32 = (int)c.cursor;
                }
                else if (v is GridLength)
                {
                    GridLength gl = (GridLength)v;
                    value.Kind = Kind.GRIDLENGTH;
                    value.u.p  = Marshal.AllocHGlobal(sizeof(GridLength));
                    Marshal.StructureToPtr(gl, value.u.p, false);                      // Unmanaged and managed structure layout is equal.
                }
                else if (v is FontStretch)
                {
                    FontStretch stretch = (FontStretch)v;
                    value.Kind = Kind.FONTSTRETCH;
                    value.u.p  = Marshal.AllocHGlobal(sizeof(UnmanagedFontStretch));
                    Marshal.StructureToPtr(stretch, value.u.p, false);                      // Unmanaged and managed structure layout is equal.
                }
                else if (v is FontStyle)
                {
                    FontStyle style = (FontStyle)v;
                    value.Kind = Kind.FONTSTYLE;
                    value.u.p  = Marshal.AllocHGlobal(sizeof(UnmanagedFontStyle));
                    Marshal.StructureToPtr(style, value.u.p, false);                      // Unmanaged and managed structure layout is equal.
                }
                else if (v is FontWeight)
                {
                    FontWeight weight = (FontWeight)v;
                    value.Kind = Kind.FONTWEIGHT;
                    value.u.p  = Marshal.AllocHGlobal(sizeof(UnmanagedFontWeight));
                    Marshal.StructureToPtr(weight, value.u.p, false);                      // Unmanaged and managed structure layout is equal.
                }
                else if (v is TextDecorationCollection)
                {
                    value.Kind  = Kind.TEXTDECORATIONS;
                    value.u.i32 = (int)(v as TextDecorationCollection).Kind;
                }
                else if (v is Type)
                {
                    Type t = v as Type;
                    value.Kind = Kind.MANAGEDTYPEINFO;
                    value.u.p  = NativeMethods.managed_type_info_new(Deployment.Current.Types.TypeToKind(t));
                }
                else if (v is Value)
                {
                    throw new InvalidOperationException("You can not create a Mono.Value from a Mono.Value.");
                }
                else
                {
                    //Console.WriteLine ("Do not know how to encode {0} yet, boxing it", v.GetType ());

                    // TODO: We probably need to marshal types that can animate as the
                    // corresponding type (Point, Double, Color, etc).
                    // TODO: We need to store the GCHandle somewhere so that we can free it,
                    // or register a callback on the surface for the unmanaged code to call.
                    GCHandle handle = GCHandle.Alloc(v);
                    value.IsGCHandle = true;
                    value.Kind       = Deployment.Current.Types.TypeToKind(v.GetType());
                    value.u.p        = GCHandle.ToIntPtr(handle);
                }
            }
            return(value);
        }
 public void PersistUntilCalled()
 {
     release_on_call = true;
     gch             = GCHandle.Alloc(this);
 }
Exemplo n.º 30
0
 private _AudioConverter()
 {
     _handle         = GCHandle.Alloc(this);
     _audioConverter = new IntPtr();
 }