internal override IAsyncResult BeginExecuteUrl(string url, string method, string childHeaders, bool sendHeaders, bool addUserIndo, IntPtr token, string name, string authType, byte[] entity, AsyncCallback cb, object state)
 {
     if (((base._ecb == IntPtr.Zero) || (this._asyncResultOfExecuteUrl != null)) || (sendHeaders && this.HeadersSent()))
     {
         throw new InvalidOperationException(System.Web.SR.GetString("Cannot_execute_url_in_this_context"));
     }
     if (((entity != null) && (entity.Length > 0)) && (UnsafeNativeMethods.EcbGetExecUrlEntityInfo(entity.Length, entity, out this._entity) != 1))
     {
         throw new HttpException(System.Web.SR.GetString("Failed_to_execute_url"));
     }
     HttpAsyncResult result = new HttpAsyncResult(cb, state);
     this._asyncResultOfExecuteUrl = result;
     this._executeUrlCompletionCallback = new ISAPIAsyncCompletionCallback(this.OnExecuteUrlCompletion);
     this._rootedThis = GCHandle.Alloc(this);
     if (UnsafeNativeMethods.EcbExecuteUrlUnicode(base._ecb, url, method, childHeaders, sendHeaders, addUserIndo, token, name, authType, this._entity, this._executeUrlCompletionCallback) != 1)
     {
         if (this._entity != IntPtr.Zero)
         {
             UnsafeNativeMethods.EcbFreeExecUrlEntityInfo(this._entity);
         }
         this._rootedThis.Free();
         this._asyncResultOfExecuteUrl = null;
         throw new HttpException(System.Web.SR.GetString("Failed_to_execute_url"));
     }
     if (sendHeaders)
     {
         this._headersSentFromExecuteUrl = true;
     }
     return result;
 }
        public TestCompleteClientWrapper()
        {
            // Access to the COM objects requires elevated permissions
            if (!IsAdministrator)
            {
                throw new ApplicationException("You must run this application with Administrator permissions");
            }

            // create the COM instance
            try
            {
                this._comInstance = Marshal.GetActiveObject(_progID);
            }
            catch
            {
                try
                {
                    this._comInstance = Activator.CreateInstance(Type.GetTypeFromProgID(_progID));
                }
                catch (Exception ex)
                {
                    System.Windows.Forms.MessageBox.Show("An exception occurred: " + ex.Message);
                }
            }

            this._instanceHandle = GCHandle.Alloc(this._comInstance, GCHandleType.Normal);

            this._manager = (TestComplete.ITestCompleteCOMManager)_comInstance;
            this._manager.Visible = true;
            this.Client = _manager.Integration;
            this.IsActive = this.Client != null;
        }
Exemple #3
0
        public static VBO<Vector3> BufferData(VBO<Vector3> vbo, Vector3[] data, GCHandle handle)
        {
            if (vbo == null) return new VBO<Vector3>(data, BufferTarget.ArrayBuffer, BufferUsageHint.StaticDraw);

            vbo.BufferSubDataPinned(BufferTarget.ArrayBuffer, 12 * data.Length, handle.AddrOfPinnedObject());
            return vbo;
        }
 public void ReadStart(
     Func<UvStreamHandle, int, object, Libuv.uv_buf_t> allocCallback,
     Action<UvStreamHandle, int, Exception, object> readCallback,
     object state)
 {
     if (_readVitality.IsAllocated)
     {
         throw new InvalidOperationException("TODO: ReadStop must be called before ReadStart may be called again");
     }
     try
     {
         _allocCallback = allocCallback;
         _readCallback = readCallback;
         _readState = state;
         _readVitality = GCHandle.Alloc(this, GCHandleType.Normal);
         _uv.read_start(this, _uv_alloc_cb, _uv_read_cb);
     }
     catch
     {
         _allocCallback = null;
         _readCallback = null;
         _readState = null;
         if (_readVitality.IsAllocated)
         {
             _readVitality.Free();
         }
         throw;
     }
 }
 public MemoryPoolSlab(byte[] data)
 {
     _data = data;
     _gcHandle = GCHandle.Alloc(data, GCHandleType.Pinned);
     _nativePointer = _gcHandle.AddrOfPinnedObject();
     _isActive = true;
 }
 protected override void Initialize()
 {
     optionsgchandle = GCHandle.Alloc(options, GCHandleType.Pinned);
     opaque = optionsgchandle.AddrOfPinnedObject();
     hoedown_html_toc_renderer_new(ref callbacks, opaque, 0);
     base.Initialize();
 }
        public MarshalMultipleValueStructure(byte[] key, byte[][] values)
        {
            if (values == null)
                throw new ArgumentNullException(nameof(values));

            _size = GetSize(values);
            _count = GetCount(values);
            _flattened = values.SelectMany(x => x).ToArray();
            _valuesHandle = GCHandle.Alloc(_flattened, GCHandleType.Pinned);

            _key = key;
            _keyHandle = GCHandle.Alloc(_key, GCHandleType.Pinned);

            Values = new[]
            {
                new ValueStructure
                {
                    size = new IntPtr(_size),
                    data = _valuesHandle.AddrOfPinnedObject()
                },
                new ValueStructure
                {
                    size = new IntPtr(_count)
                }
            };

            Key = new ValueStructure
            {
                size = new IntPtr(_key.Length),
                data = _keyHandle.AddrOfPinnedObject()
            };
        }
        public void Unpin()
        {
            if (_operationHandle.IsAllocated)
            {
                Debug.Assert(_handlesOpenWithCallback == 0);

                // This method only gets called when the WinHTTP request/websocket handles are fully closed and thus
                // all async operations are done. So, it is safe at this point to unpin the buffers and release
                // the strong GCHandle for this object.
                if (_cachedReceivePinnedBuffer.IsAllocated)
                {
                    _cachedReceivePinnedBuffer.Free();
                    _cachedReceivePinnedBuffer = default(GCHandle);
                }

                if (_cachedSendPinnedBuffer.IsAllocated)
                {
                    _cachedSendPinnedBuffer.Free();
                    _cachedSendPinnedBuffer = default(GCHandle);
                }

                _operationHandle.Free();
                _operationHandle = default(GCHandle);
            }
        }
        /// <summary>
        /// imageHelper Constructor passing in width and height and whether we want to tilt the feature
        /// </summary>
        /// <param name="pWidth"></param>
        /// <param name="pHeight"></param>
        /// <param name="pComputeTilted"></param>
        protected ImageHelper(int pWidth, int pHeight, bool pComputeTilted)
        {
            // figure out the width and height for each
            this.iWidth = pWidth;
            this.iHeight = pHeight;

            this.nWidth = pWidth + 1;
            this.nHeight = pHeight + 1;

            this.tWidth = pWidth + 2;
            this.tHeight = pHeight + 2;

            // grab the image and create a GCHandle pointer to the memory for that image
            this.integralImage = new int[nHeight, nWidth];
            this.intPointer = GCHandle.Alloc(integralImage, GCHandleType.Pinned);
            this.intImage = (int*)intPointer.AddrOfPinnedObject().ToPointer();

            this.squaredIntImage = new int[nHeight, nWidth];
            this.squaredPointer = GCHandle.Alloc(squaredIntImage, GCHandleType.Pinned);
            this.squaredImage = (int*)squaredPointer.AddrOfPinnedObject().ToPointer();

            if (pComputeTilted)
            {
                this.tiltedIntImage = new int[tHeight, tWidth];
                this.tiltedPointer = GCHandle.Alloc(tiltedIntImage, GCHandleType.Pinned);
                this.tiltedImage = (int*)tiltedPointer.AddrOfPinnedObject().ToPointer();
            }
        }
 public void Shutdown(UvStreamHandle handle, Action<UvShutdownReq, int, object> callback, object state)
 {
     _callback = callback;
     _state = state;
     _pin = GCHandle.Alloc(this, GCHandleType.Normal);
     _uv.shutdown(this, handle, _uv_shutdown_cb);
 }
 public unsafe DecomposedResult(int maxInstructions)
 {
     MaxInstructions = maxInstructions;
       _instMem = new byte[maxInstructions * sizeof(DecomposedInstructionStruct)];
       _gch = GCHandle.Alloc(_instMem, GCHandleType.Pinned);
       _instructionsPointer = (DecomposedInstructionStruct *)_gch.AddrOfPinnedObject();
 }
Exemple #12
0
 public unsafe PinnedMetadata(ImmutableArray<byte> metadata)
 {
     _bytes = GCHandle.Alloc(metadata.DangerousGetUnderlyingArray(), GCHandleType.Pinned);
     this.Pointer = _bytes.AddrOfPinnedObject();
     this.Size = metadata.Length;
     this.Reader = new MetadataReader((byte*)this.Pointer, this.Size, MetadataReaderOptions.None, null);
 }
Exemple #13
0
    internal SQLite3(SQLiteDateFormats fmt)
      : base(fmt)
    {
#if MONOTOUCH
      gch = GCHandle.Alloc (this);
#endif
    }
        public unsafe static Image LoadFromMemory(IntPtr pSource, int size, bool makeACopy, GCHandle? handle)
        {
            using (var memoryStream = new UnmanagedMemoryStream((byte*)pSource, size))
            using (var bitmap = (Bitmap)BitmapFactory.DecodeStream(memoryStream))
            {
                var bitmapData = bitmap.LockPixels();
            
                var image = Image.New2D(bitmap.Width, bitmap.Height, 1, PixelFormat.B8G8R8A8_UNorm, 1, bitmap.RowBytes);
#if SILICONSTUDIO_PARADOX_GRAPHICS_API_OPENGLES
                // Directly load image as RGBA instead of BGRA, because OpenGL ES devices don't support it out of the box (extension).
                CopyMemoryBGRA(image.PixelBuffer[0].DataPointer, bitmapData, image.PixelBuffer[0].BufferStride);
#else
                Utilities.CopyMemory(image.PixelBuffer[0].DataPointer, bitmapData, image.PixelBuffer[0].BufferStride);
#endif
                bitmap.UnlockPixels();
            
                if (handle != null)
                    handle.Value.Free();
                else if (!makeACopy)
                    Utilities.FreeMemory(pSource);
            
                return image;
            }

        }
        private WebSocketBuffer(ArraySegment<byte> internalBuffer, int receiveBufferSize, int sendBufferSize)
        {
            Contract.Assert(internalBuffer != null, "'internalBuffer' MUST NOT be NULL.");
            Contract.Assert(receiveBufferSize >= MinReceiveBufferSize,
                "'receiveBufferSize' MUST be at least " + MinReceiveBufferSize.ToString(NumberFormatInfo.InvariantInfo) + ".");
            Contract.Assert(sendBufferSize >= MinSendBufferSize,
                "'sendBufferSize' MUST be at least " + MinSendBufferSize.ToString(NumberFormatInfo.InvariantInfo) + ".");
            Contract.Assert(receiveBufferSize <= MaxBufferSize,
                "'receiveBufferSize' MUST NOT exceed " + MaxBufferSize.ToString(NumberFormatInfo.InvariantInfo) + ".");
            Contract.Assert(sendBufferSize <= MaxBufferSize,
                "'sendBufferSize' MUST NOT exceed  " + MaxBufferSize.ToString(NumberFormatInfo.InvariantInfo) + ".");

            m_ReceiveBufferSize = receiveBufferSize;
            m_SendBufferSize = sendBufferSize;
            m_InternalBuffer = internalBuffer;
            m_GCHandle = GCHandle.Alloc(internalBuffer.Array, GCHandleType.Pinned);
            // Size of the internal buffer owned exclusively by the WSPC.
            int nativeBufferSize = m_ReceiveBufferSize + m_SendBufferSize + NativeOverheadBufferSize;
            m_StartAddress = Marshal.UnsafeAddrOfPinnedArrayElement(internalBuffer.Array, internalBuffer.Offset).ToInt64();
            m_EndAddress = m_StartAddress + nativeBufferSize;
            m_NativeBuffer = new ArraySegment<byte>(internalBuffer.Array, internalBuffer.Offset, nativeBufferSize);
            m_PayloadBuffer = new ArraySegment<byte>(internalBuffer.Array,
                m_NativeBuffer.Offset + m_NativeBuffer.Count, 
                m_ReceiveBufferSize);
            m_PropertyBuffer = new ArraySegment<byte>(internalBuffer.Array,
                m_PayloadBuffer.Offset + m_PayloadBuffer.Count,
                s_PropertyBufferSize);
            m_SendBufferState = SendBufferState.None;
        }
        /// <summary>
        ///   Constructs a new Integral image of the given size.
        /// </summary>
        /// 
        protected IntegralImage2(int width, int height, bool computeTilted)
        {
            this.width = width;
            this.height = height;

            this.nWidth = width + 1;
            this.nHeight = height + 1;

            this.tWidth = width + 2;
            this.tHeight = height + 2;

            this.nSumImage = new int[nHeight, nWidth];
            this.nSumHandle = GCHandle.Alloc(nSumImage, GCHandleType.Pinned);
            this.nSum = (int*)nSumHandle.AddrOfPinnedObject().ToPointer();

            this.sSumImage = new int[nHeight, nWidth];
            this.sSumHandle = GCHandle.Alloc(sSumImage, GCHandleType.Pinned);
            this.sSum = (int*)sSumHandle.AddrOfPinnedObject().ToPointer();

            if (computeTilted)
            {
                this.tSumImage = new int[tHeight, tWidth];
                this.tSumHandle = GCHandle.Alloc(tSumImage, GCHandleType.Pinned);
                this.tSum = (int*)tSumHandle.AddrOfPinnedObject().ToPointer();
            }
        }
Exemple #17
0
        public static void Draw3DPlotLeft(float[] data, float depth, Vector3 color, Matrix4 viewMatrix, bool log = false)
        {
            if (data.Length < 441) throw new ArgumentException("The argument data was not the correct length.");

            for (int i = 0; i < fftData.Length; i++)
                fftData[i] = new Vector3((log ? Math.Log10(i) * 166 : i) - 441 / 2f, Math.Max(-200, Math.Min(200, 200 * data[i])), depth);
                //fftData[i] = new Vector3(i - 441 / 2f, Math.Max(-200, Math.Min(200, 200 * data[i])), depth);

            if (fftVAO == null)
            {
                int[] array = new int[441];
                for (int i = 0; i < array.Length; i++) array[i] = i;

                fftHandle = GCHandle.Alloc(fftData, GCHandleType.Pinned);
                fftVBO = BufferData(fftVBO, fftData, fftHandle);
                fftVAO = new VAO<Vector3>(Shaders.SimpleColoredShader, fftVBO, "in_position", new VBO<int>(array, BufferTarget.ElementArrayBuffer, BufferUsageHint.StaticDraw));
                fftVAO.DrawMode = BeginMode.LineStrip;
            }
            else fftVBO = BufferData(fftVBO, fftData, fftHandle);

            Shaders.SimpleColoredShader.Use();
            Shaders.SimpleColoredShader["projectionMatrix"].SetValue(Program.uiProjectionMatrix);
            Shaders.SimpleColoredShader["viewMatrix"].SetValue(viewMatrix);
            Shaders.SimpleColoredShader["modelMatrix"].SetValue(Matrix4.CreateTranslation(new Vector3(72 + 441 / 2f, 288, 0)));
            Shaders.SimpleColoredShader["color"].SetValue(color);
            fftVAO.Draw();
        }
 public FpuRegisters()
 {
     m_Regs = new ulong[32];
     m_RegHandle = GCHandle.Alloc(m_Regs, GCHandleType.Pinned);
     m_RegsPtr = m_RegHandle.AddrOfPinnedObject();
     /* TODO: Free handle on dispose */
 }
Exemple #19
0
        public static unsafe Image LoadFromMemory(IntPtr pSource, int size, bool makeACopy, GCHandle? handle)
        {
            var stream = new BinarySerializationReader(new NativeMemoryStream((byte*)pSource, size));

            // Read and check magic code
            var magicCode = stream.ReadUInt32();
            if (magicCode != MagicCode)
                return null;

            // Read header
            var imageDescription = new ImageDescription();
            imageDescriptionSerializer.Serialize(ref imageDescription, ArchiveMode.Deserialize, stream);

            if (makeACopy)
            {
                var buffer = Utilities.AllocateMemory(size);
                Utilities.CopyMemory(buffer, pSource, size);
                pSource = buffer;
                makeACopy = false;
            }

            var image = new Image(imageDescription, pSource, 0, handle, !makeACopy);

            var totalSizeInBytes = stream.ReadInt32();
            if (totalSizeInBytes != image.TotalSizeInBytes)
                throw new InvalidOperationException("Image size is different than expected.");

            // Read image data
            stream.Serialize(image.DataPointer, image.TotalSizeInBytes);

            return image;
        }
        public void InitFFTW(int n, Int16[] x)
        {
            //create two unmanaged arrays, properly aligned
            pin = fftwf.malloc(n * sizeof(double));
            pout = fftwf.malloc(2 * n * sizeof(double));

            //create two managed arrays, possibly misalinged
            //n*2 because we are dealing with complex numbers
            fin = new double[n];
            fout = new double[2 * n]; //fout = new fftw_complex[n];

            //get handles and pin arrays so the GC doesn't move them
            hin = GCHandle.Alloc(fin, GCHandleType.Pinned);
            hout = GCHandle.Alloc(fout, GCHandleType.Pinned);

            for (int i = 0; i < n; i++)
            {
                fin[i] = (double)x[i];
            }
            Marshal.Copy(fin, 0, pin, n);
            fplan = fftw.dft_r2c_1d(n, pin, pout, fftw_flags.Estimate);
            fftwf.execute(fplan);
            Marshal.Copy(pout, fout, 0, n);
            xout = new double[n];
            for (int i = 0; i < n; i++)
            {
                //xout[i] = Math.Sqrt(Math.Pow(fout[i].re, 2.0) + Math.Pow(fout[i].im, 2.0));
                //xout[i] = Math.Sqrt(Math.Pow(fout[i*2], 2.0) + Math.Pow(fout[i*2+1], 2.0)) / 1024;
                xout[i] = Math.Sqrt(fout[i * 2] * fout[i * 2] + fout[i * 2 + 1] * fout[i * 2 + 1]);
            }
        }
Exemple #21
0
 internal CFMessagePort(IntPtr handle, bool owns)
 {
     this.handle = handle;
     gch = GCHandle.Alloc (this);
     if (!owns)
         CFObject.CFRetain (handle);
 }
Exemple #22
0
        public static void FreeString(ref GCHandle handle)
        {
            if (handle == NullHandle)
                return;

            handle.Free();
        }
        public override void CommitToSolver()
        {
            if (skinIndices != null && skinPoints != null && skinNormals != null && skinRadiiBackstops != null && skinStiffnesses != null){

                Oni.UnpinMemory(skinIndicesHandle);
                Oni.UnpinMemory(skinPointsHandle);
                Oni.UnpinMemory(skinNormalsHandle);
                Oni.UnpinMemory(skinRadiiBackstopsHandle);
                Oni.UnpinMemory(skinStiffnessesHandle);

                skinIndicesHandle = Oni.PinMemory(skinIndices);
                skinPointsHandle = Oni.PinMemory(skinPoints);
                skinNormalsHandle = Oni.PinMemory(skinNormals);
                skinRadiiBackstopsHandle = Oni.PinMemory(skinRadiiBackstops);
                skinStiffnessesHandle = Oni.PinMemory(skinStiffnesses);

                Oni.SetSkinConstraints(solver.Solver,
                                       skinIndicesHandle.AddrOfPinnedObject(),
                                       skinPointsHandle.AddrOfPinnedObject(),
                                       skinNormalsHandle.AddrOfPinnedObject(),
                                       skinRadiiBackstopsHandle.AddrOfPinnedObject(),
                                       skinStiffnessesHandle.AddrOfPinnedObject());

                CommitActive();
            }
        }
Exemple #24
0
		public PSP(CoreComm comm, string isopath)
		{
			ServiceProvider = new BasicServiceProvider(this);
			if (attachedcore != null)
			{
				attachedcore.Dispose();
				attachedcore = null;
			}
			CoreComm = comm;

			logcallback = new PPSSPPDll.LogCB(LogCallbackFunc);

			bool good = PPSSPPDll.init(isopath, logcallback);
			LogFlush();
			if (!good)
				throw new Exception("PPSSPP Init failed!");
			vidhandle = GCHandle.Alloc(screenbuffer, GCHandleType.Pinned);
			PPSSPPDll.setvidbuff(vidhandle.AddrOfPinnedObject());

			CoreComm.VsyncDen = 1;
			CoreComm.VsyncNum = 60;
			CoreComm.RomStatusDetails = "It puts the scythe in the chicken or it gets the abyss again!";

			attachedcore = this;
		}
Exemple #25
0
 public TtsBufferManaged()
 {
     _value = new TTS_BUFFER_T();
     _pinHandle = GCHandle.Alloc(this, GCHandleType.Pinned);
     _value.MaxBufferLength = TTS_BUFFER_T.BufferSize;
     _value.DataPtr = Marshal.AllocHGlobal(TTS_BUFFER_T.BufferSize);
 }
Exemple #26
0
        static void Main(string[] args)
        {
            Console.Write("Enter Passphrase: ");
            using (var passphrase = GetPassphraseFromConsole())
            {
                Console.WriteLine("Your password:"******"Exception thrown.");
                            }

                            Marshal.ZeroFreeBSTR(ptr);

                            for (var ii = 0; ii < arPass.Length; ii++)
                            {
                                arPass[ii] = '\0';
                            }

                            handle.Free();

                        },
                            null
                        );
                }
            }
        }
Exemple #27
0
        private static void EnsureFontLoaded()
        {
            if (_FontAwesome == null)
            {
                _PrivateFontCollection = new PrivateFontCollection();

                byte[] fontAwesomeBuffer = BarFunctions.LoadFont("SystemImages.FontAwesome.ttf");
                _FontAwesomeHandle = GCHandle.Alloc(fontAwesomeBuffer, GCHandleType.Pinned);
                _PrivateFontCollection.AddMemoryFont(_FontAwesomeHandle.AddrOfPinnedObject(), fontAwesomeBuffer.Length);
                uint rsxCnt = 1;
                _FontAwesomePointer = AddFontMemResourceEx(_FontAwesomeHandle.AddrOfPinnedObject(),
                                                     (uint)fontAwesomeBuffer.Length, IntPtr.Zero, ref rsxCnt);
                using (FontFamily ff = _PrivateFontCollection.Families[0])
                {
                    if (ff.IsStyleAvailable(FontStyle.Regular))
                    {
                        _FontAwesome = new Font(ff, _FontAwesomeDefaultSize, FontStyle.Regular, GraphicsUnit.Point);
                        _FontAwesomeCache.Add(_FontAwesomeDefaultSize, _FontAwesome);
                    }
                    else
                    {
                        // Error use default font...
                        _FontAwesome = SystemInformation.MenuFont;
                    }
                }
            }
        }
Exemple #28
0
 public WaveRecorder(int deviceIndex, double sampleRate, int framesPerBuffer, AudioBufferAvailableDelegate bufferAvailable)
 {
     this._bufferAvailable = bufferAvailable;
       PaStreamParameters inputParameters = new PaStreamParameters();
       inputParameters.device = deviceIndex;
       inputParameters.channelCount = 2;
       inputParameters.suggestedLatency = 0.0;
       inputParameters.sampleFormat = PaSampleFormat.PaFloat32;
       PaError paError1 = PortAudioAPI.Pa_IsFormatSupported(ref inputParameters, IntPtr.Zero, sampleRate);
       if (paError1 != PaError.paNoError)
     throw new ApplicationException(paError1.ToString());
       this._gcHandle = GCHandle.Alloc((object) this);
       PaError paError2 = PortAudioAPI.Pa_OpenStream(out this._streamHandle, ref inputParameters, IntPtr.Zero, sampleRate, (uint) framesPerBuffer, PaStreamFlags.PaNoFlag, this._paCallback, (IntPtr) this._gcHandle);
       if (paError2 != PaError.paNoError)
       {
     this._gcHandle.Free();
     throw new ApplicationException(paError2.ToString());
       }
       PaError paError3 = PortAudioAPI.Pa_StartStream(this._streamHandle);
       if (paError3 != PaError.paNoError)
       {
     int num = (int) PortAudioAPI.Pa_CloseStream(this._streamHandle);
     this._gcHandle.Free();
     throw new ApplicationException(paError3.ToString());
       }
 }
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="aDevice">Device which owns this provider</param>
 protected DvProviderUpnpOrgSwitchPower1(DvDevice aDevice)
     : base(aDevice, "upnp.org", "SwitchPower", 1)
 {
     iGch = GCHandle.Alloc(this);
     iPropertyStatus = new PropertyBool(new ParameterBool("Status"));
     AddProperty(iPropertyStatus);
 }
Exemple #30
0
        public static string MongoPasswordDigest(string username, SecureString password)
        {
            using (var md5 = MD5.Create())
            {
                var bytes = Utf8Encodings.Strict.GetBytes(username + ":mongo:");

                IntPtr unmanagedPassword = IntPtr.Zero;
                try
                {
                    unmanagedPassword = Marshal.SecureStringToBSTR(password);
                    var passwordChars = new char[password.Length];
                    GCHandle passwordCharsHandle = new GCHandle();
                    try
                    {
                        passwordCharsHandle = GCHandle.Alloc(passwordChars, GCHandleType.Pinned);
                        Marshal.Copy(unmanagedPassword, passwordChars, 0, passwordChars.Length);

                        var byteCount = Utf8Encodings.Strict.GetByteCount(passwordChars);
                        var passwordBytes = new byte[byteCount];
                        GCHandle passwordBytesHandle = new GCHandle();
                        try
                        {
                            passwordBytesHandle = GCHandle.Alloc(passwordBytesHandle, GCHandleType.Pinned);
                            Utf8Encodings.Strict.GetBytes(passwordChars, 0, passwordChars.Length, passwordBytes, 0);

                            var buffer = new byte[bytes.Length + passwordBytes.Length];
                            Buffer.BlockCopy(bytes, 0, buffer, 0, bytes.Length);
                            Buffer.BlockCopy(passwordBytes, 0, buffer, bytes.Length, passwordBytes.Length);

                            return BsonUtils.ToHexString(md5.ComputeHash(buffer));
                        }
                        finally
                        {
                            Array.Clear(passwordBytes, 0, passwordBytes.Length);

                            if (passwordBytesHandle.IsAllocated)
                            {
                                passwordBytesHandle.Free();
                            }
                        }
                    }
                    finally
                    {
                        Array.Clear(passwordChars, 0, passwordChars.Length);

                        if (passwordCharsHandle.IsAllocated)
                        {
                            passwordCharsHandle.Free();
                        }
                    }
                }
                finally
                {
                    if (unmanagedPassword != IntPtr.Zero)
                    {
                        Marshal.ZeroFreeBSTR(unmanagedPassword);
                    }
                }
            }
        }
Exemple #31
0
 /// <summary>
 /// 清除記憶體
 /// </summary>
 private void Clear(string sSecretKey)
 {
     // For additional security Pin the key.
     System.Runtime.InteropServices.GCHandle Gch = System.Runtime.InteropServices.GCHandle.Alloc(sSecretKey, System.Runtime.InteropServices.GCHandleType.Pinned);
     // Remove the Key from memory.
     ZeroMemory(Gch.AddrOfPinnedObject(), sSecretKey.Length * 2);
     Gch.Free();
 }
Exemple #32
0
    public virtual void Run()
    {
        int        instance = Kernel.GetModuleHandle(null);
        WndClassEx wndclass = new WndClassEx();
        Msg        msg      = new Msg();
        String     clName   = "Entry Area";

        Win32.WinCB wcb = new Win32.WinCB(this.CallBack);
        root = System.Runtime.InteropServices.GCHandle.Alloc(wcb);

        wndclass.cbSize        = System.Runtime.InteropServices.Marshal.SizeOf(wndclass);
        wndclass.style         = ClassStyle.HRedraw | ClassStyle.VRedraw;
        wndclass.lpfnWndProc   = wcb;
        wndclass.cbClsExtra    = 0;
        wndclass.cbWndExtra    = 0;
        wndclass.hInstance     = instance;
        this.instance          = instance;
        wndclass.hIcon         = User.LoadIcon(0, IconID.Application);
        wndclass.hCursor       = User.LoadCursor(0, CursorID.Arrow);
        wndclass.hbrBackground = GDI.GetStockObject(Brush.White);

        wndclass.lpszMenuName  = null;
        wndclass.lpszClassName = clName;
        wndclass.hIconSm       = User.LoadIcon(0, IconID.Application);

        if (User.RegisterClassExA(wndclass) == 0)
        {
            throw new System.ApplicationException("Unable to Register Entry Dialog");
        }

        wnd = User.CreateWindowEx(0, clName, clName, WinStyle.OverlappedWindow,
                                  0, 0, xDim, yDim, 0, 0, instance, 0);

        if (wnd == 0)
        {
            throw new System.ApplicationException(Error.GetSystemErrorMessage());
        }

        User.ShowWindow(wnd, ShowWindow.ShowNormal);
        User.UpdateWindow(wnd);

        while (User.GetMessage(msg, 0, 0, 0) != 0)
        {
            User.TranslateMessage(msg);
            User.DispatchMessage(msg);
        }

        root.Free();
    }
Exemple #33
0
 protected SafeGCHandle(System.Runtime.InteropServices.GCHandle gcHandle) : this()
 {
     base.SetHandle(System.Runtime.InteropServices.GCHandle.ToIntPtr(gcHandle));
 }
Exemple #34
0
 private void TakeHandle(ref System.Runtime.InteropServices.GCHandle gcHandle)
 {
     base.SetHandle(System.Runtime.InteropServices.GCHandle.ToIntPtr(gcHandle));
     gcHandle = new System.Runtime.InteropServices.GCHandle();
 }
Exemple #35
0
 public static IntPtr ToIntPtr(GCHandle value)
 {
     return(value._handle);
 }
Exemple #36
0
        private static tCLIFile *LoadPEFile(byte[] image)
        {
            tCLIFile *pRet = ((tCLIFile *)Mem.malloc((SIZE_T)sizeof(tCLIFile)));

            System.Runtime.InteropServices.GCHandle handle = System.Runtime.InteropServices.GCHandle.Alloc(image, GCHandleType.Pinned);
            byte *pData = (byte *)handle.AddrOfPinnedObject();

            byte *pMSDOSHeader = (byte *)&(((byte *)pData)[0]);
            byte *pPEHeader;
            byte *pPEOptionalHeader;
            byte *pPESectionHeaders;
            byte *pCLIHeader;
            byte *pRawMetaData;

            int    i;
            uint   lfanew;
            ushort machine;
            int    numSections;
            //uint imageBase;
            //int fileAlignment;
            uint cliHeaderRVA;
            //uint cliHeaderSize;
            uint metaDataRVA;
            //uint metaDataSize;
            tMetaData *pMetaData;

            pRet->pRVA      = RVA.New();
            pRet->gcHandle  = (PTR)(System.IntPtr)handle;
            pRet->pMetaData = pMetaData = MetaData.New();

            lfanew            = *(uint *)&(pMSDOSHeader[0x3c]);
            pPEHeader         = pMSDOSHeader + lfanew + 4;
            pPEOptionalHeader = pPEHeader + 20;
            pPESectionHeaders = pPEOptionalHeader + 224;

            machine = *(ushort *)&(pPEHeader[0]);
            if (machine != DOT_NET_MACHINE)
            {
                return(null);
            }
            numSections = *(ushort *)&(pPEHeader[2]);

            //imageBase = *(uint*)&(pPEOptionalHeader[28]);
            //fileAlignment = *(int*)&(pPEOptionalHeader[36]);

            for (i = 0; i < numSections; i++)
            {
                byte *pSection = pPESectionHeaders + i * 40;
                RVA.Create(pRet->pRVA, pData, pSection);
            }

            cliHeaderRVA = *(uint *)&(pPEOptionalHeader[208]);
            //cliHeaderSize = *(uint*)&(pPEOptionalHeader[212]);

            pCLIHeader = (byte *)RVA.FindData(pRet->pRVA, cliHeaderRVA);

            metaDataRVA = *(uint *)&(pCLIHeader[8]);
            //metaDataSize = *(uint*)&(pCLIHeader[12]);
            pRet->entryPoint = *(uint *)&(pCLIHeader[20]);
            pRawMetaData     = (byte *)RVA.FindData(pRet->pRVA, metaDataRVA);

            // Load all metadata
            {
                uint  versionLen = *(uint *)&(pRawMetaData[12]);
                uint  ofs, numberOfStreams;
                void *pTableStream    = null;
                uint  tableStreamSize = 0;
                pRet->pVersion = &(pRawMetaData[16]);
                Sys.log_f(1, "CLI version: %s\n", (PTR)pRet->pVersion);
                ofs             = 16 + versionLen;
                numberOfStreams = *(ushort *)&(pRawMetaData[ofs + 2]);
                ofs            += 4;

                for (i = 0; i < (int)numberOfStreams; i++)
                {
                    uint  streamOffset = *(uint *)&pRawMetaData[ofs];
                    uint  streamSize   = *(uint *)&pRawMetaData[ofs + 4];
                    byte *pStreamName  = &pRawMetaData[ofs + 8];
                    void *pStream      = pRawMetaData + streamOffset;
                    ofs += (uint)((S.strlen(pStreamName) + 4) & (~0x3)) + 8;
                    if (S.strcasecmp(pStreamName, "#Strings") == 0)
                    {
                        MetaData.LoadStrings(pMetaData, pStream, streamSize);
                    }
                    else if (S.strcasecmp(pStreamName, "#US") == 0)
                    {
                        MetaData.LoadUserStrings(pMetaData, pStream, streamSize);
                    }
                    else if (S.strcasecmp(pStreamName, "#Blob") == 0)
                    {
                        MetaData.LoadBlobs(pMetaData, pStream, streamSize);
                    }
                    else if (S.strcasecmp(pStreamName, "#GUID") == 0)
                    {
                        MetaData.LoadGUIDs(pMetaData, pStream, streamSize);
                    }
                    else if (S.strcasecmp(pStreamName, "#~") == 0)
                    {
                        pTableStream    = pStream;
                        tableStreamSize = streamSize;
                    }
                }
                // Must load tables last
                if (pTableStream != null)
                {
                    MetaData.LoadTables(pMetaData, pRet->pRVA, pTableStream, (uint)tableStreamSize);
                }
            }

            // Mark all generic definition type and methods as such
            for (i = (int)pMetaData->tables.numRows[MetaDataTable.MD_TABLE_GENERICPARAM]; i > 0; i--)
            {
                tMD_GenericParam * pGenericParam;
                /*IDX_TABLE*/ uint ownerIdx;

                pGenericParam = (tMD_GenericParam *)MetaData.GetTableRow
                                    (pMetaData, MetaData.MAKE_TABLE_INDEX(MetaDataTable.MD_TABLE_GENERICPARAM, (uint)i));
                ownerIdx = pGenericParam->owner;
                switch (MetaData.TABLE_ID(ownerIdx))
                {
                case MetaDataTable.MD_TABLE_TYPEDEF:
                {
                    tMD_TypeDef *pTypeDef = (tMD_TypeDef *)MetaData.GetTableRow(pMetaData, ownerIdx);
                    pTypeDef->isGenericDefinition = 1;
                }
                break;

                case MetaDataTable.MD_TABLE_METHODDEF:
                {
                    tMD_MethodDef *pMethodDef = (tMD_MethodDef *)MetaData.GetTableRow(pMetaData, ownerIdx);
                    pMethodDef->isGenericDefinition = 1;
                }
                break;

                default:
                    Sys.Crash("Wrong generic parameter owner: 0x%08x", ownerIdx);
                    break;
                }
            }

            // Mark all nested classes as such
            for (i = (int)pMetaData->tables.numRows[MetaDataTable.MD_TABLE_NESTEDCLASS]; i > 0; i--)
            {
                tMD_NestedClass *pNested;
                tMD_TypeDef *    pParent;
                tMD_TypeDef *    pChild;

                pNested           = (tMD_NestedClass *)MetaData.GetTableRow(pMetaData, MetaData.MAKE_TABLE_INDEX(MetaDataTable.MD_TABLE_NESTEDCLASS, (uint)i));
                pParent           = (tMD_TypeDef *)MetaData.GetTableRow(pMetaData, pNested->enclosingClass);
                pChild            = (tMD_TypeDef *)MetaData.GetTableRow(pMetaData, pNested->nestedClass);
                pChild->pNestedIn = pParent;
            }

            return(pRet);
        }
Exemple #37
0
        public static Tensor ReadTensorFromImageFile <T>(
            String fileName,
            int inputHeight     = -1,
            int inputWidth      = -1,
            float inputMean     = 0.0f,
            float scale         = 1.0f,
            bool flipUpSideDown = false,
            bool swapBR         = false) where T : struct
        {
#if __ANDROID__
            return(NativeReadTensorFromImageFile <T>(fileName, inputHeight, inputWidth, inputMean, scale,
                                                     flipUpSideDown, swapBR));
#elif __IOS__
            UIImage image = new UIImage(fileName);
            if (inputHeight > 0 || inputWidth > 0)
            {
                UIImage resized = image.Scale(new CGSize(inputWidth, inputHeight));
                image.Dispose();
                image = resized;
            }
            int[]   intValues   = new int[(int)(image.Size.Width * image.Size.Height)];
            float[] floatValues = new float[(int)(image.Size.Width * image.Size.Height * 3)];
            System.Runtime.InteropServices.GCHandle handle = System.Runtime.InteropServices.GCHandle.Alloc(intValues, System.Runtime.InteropServices.GCHandleType.Pinned);
            using (CGImage cgimage = image.CGImage)
                using (CGColorSpace cspace = CGColorSpace.CreateDeviceRGB())
                    using (CGBitmapContext context = new CGBitmapContext(
                               handle.AddrOfPinnedObject(),
                               (nint)image.Size.Width,
                               (nint)image.Size.Height,
                               8,
                               (nint)image.Size.Width * 4,
                               cspace,
                               CGImageAlphaInfo.PremultipliedLast
                               ))
                    {
                        context.DrawImage(new CGRect(new CGPoint(), image.Size), cgimage);
                    }
            handle.Free();

            for (int i = 0; i < intValues.Length; ++i)
            {
                int val = intValues[i];
                floatValues[i * 3 + 0] = (((val >> 16) & 0xFF) - inputMean) * scale;
                floatValues[i * 3 + 1] = (((val >> 8) & 0xFF) - inputMean) * scale;
                floatValues[i * 3 + 2] = ((val & 0xFF) - inputMean) * scale;
            }

            Tensor t = new Tensor(DataType.Float, new int[] { 1, (int)image.Size.Height, (int)image.Size.Width, 3 });
            System.Runtime.InteropServices.Marshal.Copy(floatValues, 0, t.DataPointer, floatValues.Length);
            return(t);
#else
            FileInfo fi        = new FileInfo(fileName);
            String   extension = fi.Extension.ToLower();

            //Use tensorflow to decode the following image formats
            if ((typeof(T) == typeof(float))
                &&
                (extension.Equals(".jpeg") ||
                 extension.Equals(".jpg") ||
                 extension.Equals(".png") ||
                 extension.Equals(".gif")))
            {
                using (Graph graph = new Graph())
                {
                    Operation input = graph.Placeholder(DataType.String);

                    //output dimension [height, width, 3] where 3 is the number of channels
                    //DecodeJpeg can decode JPEG, PNG and GIF
                    Operation jpegDecoder = graph.DecodeJpeg(input, 3);

                    Operation floatCaster = graph.Cast(jpegDecoder, DstT: DataType.Float); //cast to float

                    Tensor    zeroConst    = new Tensor(0);
                    Operation zeroConstOp  = graph.Const(zeroConst, zeroConst.Type, opName: "zeroConstOp");
                    Operation dimsExpander = graph.ExpandDims(floatCaster, zeroConstOp); //turn it to dimension [1, height, width, 3]

                    Operation resized;
                    bool      resizeRequired = (inputHeight > 0) && (inputWidth > 0);
                    if (resizeRequired)
                    {
                        Tensor    size   = new Tensor(new int[] { inputHeight, inputWidth }); // new size;
                        Operation sizeOp = graph.Const(size, size.Type, opName: "size");
                        resized = graph.ResizeBilinear(dimsExpander, sizeOp);                 //resize image
                    }
                    else
                    {
                        resized = dimsExpander;
                    }

                    Tensor    mean       = new Tensor(inputMean);
                    Operation meanOp     = graph.Const(mean, mean.Type, opName: "mean");
                    Operation subtracted = graph.Sub(resized, meanOp);

                    Tensor    scaleTensor = new Tensor(scale);
                    Operation scaleOp     = graph.Const(scaleTensor, scaleTensor.Type, opName: "scale");
                    Operation scaled      = graph.Mul(subtracted, scaleOp);

                    Operation swapedBR;
                    if (swapBR)
                    {
                        Tensor    threeConst   = new Tensor(new int[] { 3 });
                        Operation threeConstOp = graph.Const(threeConst, threeConst.Type, "threeConstOp");
                        swapedBR = graph.ReverseV2(scaled, threeConstOp, "swapBR");
                    }
                    else
                    {
                        swapedBR = scaled;
                    }

                    Operation flipped;
                    if (flipUpSideDown)
                    {
                        Tensor    oneConst   = new Tensor(new int[] { 1 });
                        Operation oneConstOp = graph.Const(oneConst, oneConst.Type, "oneConstOp");
                        flipped = graph.ReverseV2(swapedBR, oneConstOp, "flipUpSideDownOp");
                    }
                    else
                    {
                        flipped = swapedBR;
                    }

                    using (Session session = new Session(graph))
                    {
                        Tensor imageTensor = Tensor.FromString(File.ReadAllBytes(fileName));

                        Tensor[] imageResults = session.Run(new Output[] { input }, new Tensor[] { imageTensor },
                                                            new Output[] { flipped });
                        return(imageResults[0]);
                    }
                }
            }
            else
            {
                return(NativeReadTensorFromImageFile <T>(fileName, inputHeight, inputWidth, inputMean, scale,
                                                         flipUpSideDown, swapBR));
            }
#endif
        }
Exemple #38
0
        public static void ReadImageFileToTensor <T>(
            String fileName,
            IntPtr dest,
            int inputHeight = -1,
            int inputWidth  = -1,
            float inputMean = 0.0f,
            float scale     = 1.0f)
        {
#if __ANDROID__
            Android.Graphics.Bitmap bmp = BitmapFactory.DecodeFile(fileName);

            if (inputHeight > 0 || inputWidth > 0)
            {
                Bitmap resized = Bitmap.CreateScaledBitmap(bmp, inputWidth, inputHeight, false);
                bmp.Dispose();
                bmp = resized;
            }
            int[]   intValues   = new int[bmp.Width * bmp.Height];
            float[] floatValues = new float[bmp.Width * bmp.Height * 3];
            bmp.GetPixels(intValues, 0, bmp.Width, 0, 0, bmp.Width, bmp.Height);
            for (int i = 0; i < intValues.Length; ++i)
            {
                int val = intValues[i];
                floatValues[i * 3 + 0] = (((val >> 16) & 0xFF) - inputMean) * scale;
                floatValues[i * 3 + 1] = (((val >> 8) & 0xFF) - inputMean) * scale;
                floatValues[i * 3 + 2] = ((val & 0xFF) - inputMean) * scale;
            }

            Marshal.Copy(floatValues, 0, dest, floatValues.Length);
#elif __IOS__
            UIImage image = new UIImage(fileName);
            if (inputHeight > 0 || inputWidth > 0)
            {
                UIImage resized = image.Scale(new CGSize(inputWidth, inputHeight));
                image.Dispose();
                image = resized;
            }
            int[]   intValues   = new int[(int)(image.Size.Width * image.Size.Height)];
            float[] floatValues = new float[(int)(image.Size.Width * image.Size.Height * 3)];
            System.Runtime.InteropServices.GCHandle handle = System.Runtime.InteropServices.GCHandle.Alloc(intValues, System.Runtime.InteropServices.GCHandleType.Pinned);
            using (CGImage cgimage = image.CGImage)
                using (CGColorSpace cspace = CGColorSpace.CreateDeviceRGB())
                    using (CGBitmapContext context = new CGBitmapContext(
                               handle.AddrOfPinnedObject(),
                               (nint)image.Size.Width,
                               (nint)image.Size.Height,
                               8,
                               (nint)image.Size.Width * 4,
                               cspace,
                               CGImageAlphaInfo.PremultipliedLast
                               ))
                    {
                        context.DrawImage(new CGRect(new CGPoint(), image.Size), cgimage);
                    }
            handle.Free();

            for (int i = 0; i < intValues.Length; ++i)
            {
                int val = intValues[i];
                floatValues[i * 3 + 0] = (((val >> 16) & 0xFF) - inputMean) * scale;
                floatValues[i * 3 + 1] = (((val >> 8) & 0xFF) - inputMean) * scale;
                floatValues[i * 3 + 2] = ((val & 0xFF) - inputMean) * scale;
            }
            System.Runtime.InteropServices.Marshal.Copy(floatValues, 0, dest, floatValues.Length);
#elif __UNIFIED__
            NSImage image = new NSImage(fileName);
            if (inputHeight > 0 || inputWidth > 0)
            {
                NSImage resized = new NSImage(new CGSize(inputWidth, inputHeight));
                resized.LockFocus();
                image.DrawInRect(new CGRect(0, 0, inputWidth, inputHeight), CGRect.Empty, NSCompositingOperation.SourceOver, 1.0f);
                resized.UnlockFocus();
                image.Dispose();
                image = resized;
            }
            int[]   intValues   = new int[(int)(image.Size.Width * image.Size.Height)];
            float[] floatValues = new float[(int)(image.Size.Width * image.Size.Height * 3)];
            System.Runtime.InteropServices.GCHandle handle = System.Runtime.InteropServices.GCHandle.Alloc(intValues, System.Runtime.InteropServices.GCHandleType.Pinned);
            using (CGImage cgimage = image.CGImage)
                using (CGColorSpace cspace = CGColorSpace.CreateDeviceRGB())
                    using (CGBitmapContext context = new CGBitmapContext(
                               handle.AddrOfPinnedObject(),
                               (nint)image.Size.Width,
                               (nint)image.Size.Height,
                               8,
                               (nint)image.Size.Width * 4,
                               cspace,
                               CGImageAlphaInfo.PremultipliedLast
                               ))
                    {
                        context.DrawImage(new CGRect(new CGPoint(), image.Size), cgimage);
                    }
            handle.Free();

            for (int i = 0; i < intValues.Length; ++i)
            {
                int val = intValues[i];
                floatValues[i * 3 + 0] = (((val >> 16) & 0xFF) - inputMean) * scale;
                floatValues[i * 3 + 1] = (((val >> 8) & 0xFF) - inputMean) * scale;
                floatValues[i * 3 + 2] = ((val & 0xFF) - inputMean) * scale;
            }
            System.Runtime.InteropServices.Marshal.Copy(floatValues, 0, dest, floatValues.Length);
#else
            if (Emgu.TF.Util.Platform.OperationSystem == OS.Windows)
            {
                //Do something for Windows
                System.Drawing.Bitmap bmp = new Bitmap(fileName);

                if (inputHeight > 0 || inputWidth > 0)
                {
                    //resize bmp
                    System.Drawing.Bitmap newBmp = new Bitmap(bmp, inputWidth, inputHeight);
                    bmp.Dispose();
                    bmp = newBmp;
                    //bmp.Save("tmp.png");
                }

                byte[] byteValues = new byte[bmp.Width * bmp.Height * 3];
                System.Drawing.Imaging.BitmapData bd = new System.Drawing.Imaging.BitmapData();

                bmp.LockBits(
                    new Rectangle(0, 0, bmp.Width, bmp.Height),
                    System.Drawing.Imaging.ImageLockMode.ReadOnly,
                    System.Drawing.Imaging.PixelFormat.Format24bppRgb, bd);
                Marshal.Copy(bd.Scan0, byteValues, 0, byteValues.Length);
                bmp.UnlockBits(bd);

                if (typeof(T) == typeof(float))
                {
                    float[] floatValues = new float[bmp.Width * bmp.Height * 3];
                    for (int i = 0; i < byteValues.Length; ++i)
                    {
                        floatValues[i] = ((float)byteValues[i] - inputMean) * scale;
                    }
                    Marshal.Copy(floatValues, 0, dest, floatValues.Length);
                }
                else if (typeof(T) == typeof(byte))
                {
                    bool swapBR = false;
                    if (swapBR)
                    {
                        int    imageSize = bmp.Width * bmp.Height;
                        byte[] bValues   = new byte[imageSize * 3];
                        for (int i = 0; i < imageSize; ++i)
                        {
                            bValues[i * 3]     = (byte)(((float)byteValues[i * 3 + 2] - inputMean) * scale);
                            bValues[i * 3 + 1] = (byte)(((float)byteValues[i * 3 + 1] - inputMean) * scale);
                            bValues[i * 3 + 2] = (byte)(((float)byteValues[i * 3 + 0] - inputMean) * scale);
                        }
                        Marshal.Copy(bValues, 0, dest, bValues.Length);
                    }
                    else
                    {
                        if (!(inputMean == 0.0f && scale == 1.0f))
                        {
                            for (int i = 0; i < byteValues.Length; ++i)
                            {
                                byteValues[i] = (byte)(((float)byteValues[i] - inputMean) * scale);
                            }
                        }
                        Marshal.Copy(byteValues, 0, dest, byteValues.Length);
                    }
                }
                else
                {
                    throw new Exception(String.Format("Destination data type {0} is not supported.", typeof(T).ToString()));
                }
            }
            else
            {
                throw new Exception("Not implemented");
            }
#endif
        }
Exemple #39
0
        public static void ReadImageFileToTensor(String fileName, IntPtr dest, int inputHeight = -1, int inputWidth = -1, float inputMean = 0.0f, float scale = 1.0f)
        {
#if __ANDROID__
            Android.Graphics.Bitmap bmp = BitmapFactory.DecodeFile(fileName);

            if (inputHeight > 0 || inputWidth > 0)
            {
                Bitmap resized = Bitmap.CreateScaledBitmap(bmp, inputWidth, inputHeight, false);
                bmp.Dispose();
                bmp = resized;
            }
            int[]   intValues   = new int[bmp.Width * bmp.Height];
            float[] floatValues = new float[bmp.Width * bmp.Height * 3];
            bmp.GetPixels(intValues, 0, bmp.Width, 0, 0, bmp.Width, bmp.Height);
            for (int i = 0; i < intValues.Length; ++i)
            {
                int val = intValues[i];
                floatValues[i * 3 + 0] = (((val >> 16) & 0xFF) - inputMean) * scale;
                floatValues[i * 3 + 1] = (((val >> 8) & 0xFF) - inputMean) * scale;
                floatValues[i * 3 + 2] = ((val & 0xFF) - inputMean) * scale;
            }

            System.Runtime.InteropServices.Marshal.Copy(floatValues, 0, dest, floatValues.Length);
#elif __IOS__
            UIImage image = new UIImage(fileName);
            if (inputHeight > 0 || inputWidth > 0)
            {
                UIImage resized = image.Scale(new CGSize(inputWidth, inputHeight));
                image.Dispose();
                image = resized;
            }
            int[]   intValues   = new int[(int)(image.Size.Width * image.Size.Height)];
            float[] floatValues = new float[(int)(image.Size.Width * image.Size.Height * 3)];
            System.Runtime.InteropServices.GCHandle handle = System.Runtime.InteropServices.GCHandle.Alloc(intValues, System.Runtime.InteropServices.GCHandleType.Pinned);
            using (CGImage cgimage = image.CGImage)
                using (CGColorSpace cspace = CGColorSpace.CreateDeviceRGB())
                    using (CGBitmapContext context = new CGBitmapContext(
                               handle.AddrOfPinnedObject(),
                               (nint)image.Size.Width,
                               (nint)image.Size.Height,
                               8,
                               (nint)image.Size.Width * 4,
                               cspace,
                               CGImageAlphaInfo.PremultipliedLast
                               ))
                    {
                        context.DrawImage(new CGRect(new CGPoint(), image.Size), cgimage);
                    }
            handle.Free();

            for (int i = 0; i < intValues.Length; ++i)
            {
                int val = intValues[i];
                floatValues[i * 3 + 0] = (((val >> 16) & 0xFF) - inputMean) * scale;
                floatValues[i * 3 + 1] = (((val >> 8) & 0xFF) - inputMean) * scale;
                floatValues[i * 3 + 2] = ((val & 0xFF) - inputMean) * scale;
            }
            System.Runtime.InteropServices.Marshal.Copy(floatValues, 0, dest, floatValues.Length);
#elif __UNIFIED__
            NSImage image = new NSImage(fileName);
            if (inputHeight > 0 || inputWidth > 0)
            {
                NSImage resized = new NSImage(new CGSize(inputWidth, inputHeight));
                resized.LockFocus();
                image.DrawInRect(new CGRect(0, 0, inputWidth, inputHeight), CGRect.Empty, NSCompositingOperation.SourceOver, 1.0f);
                resized.UnlockFocus();
                image.Dispose();
                image = resized;
            }
            int[]   intValues   = new int[(int)(image.Size.Width * image.Size.Height)];
            float[] floatValues = new float[(int)(image.Size.Width * image.Size.Height * 3)];
            System.Runtime.InteropServices.GCHandle handle = System.Runtime.InteropServices.GCHandle.Alloc(intValues, System.Runtime.InteropServices.GCHandleType.Pinned);
            using (CGImage cgimage = image.CGImage)
                using (CGColorSpace cspace = CGColorSpace.CreateDeviceRGB())
                    using (CGBitmapContext context = new CGBitmapContext(
                               handle.AddrOfPinnedObject(),
                               (nint)image.Size.Width,
                               (nint)image.Size.Height,
                               8,
                               (nint)image.Size.Width * 4,
                               cspace,
                               CGImageAlphaInfo.PremultipliedLast
                               ))
                    {
                        context.DrawImage(new CGRect(new CGPoint(), image.Size), cgimage);
                    }
            handle.Free();

            for (int i = 0; i < intValues.Length; ++i)
            {
                int val = intValues[i];
                floatValues[i * 3 + 0] = (((val >> 16) & 0xFF) - inputMean) * scale;
                floatValues[i * 3 + 1] = (((val >> 8) & 0xFF) - inputMean) * scale;
                floatValues[i * 3 + 2] = ((val & 0xFF) - inputMean) * scale;
            }
            System.Runtime.InteropServices.Marshal.Copy(floatValues, 0, dest, floatValues.Length);
#else
            throw new Exception("Not implemented");
#endif
        }
Exemple #40
0
 internal static StreamAsIStream FromSD(ref StreamDescriptor sd)
 {
     Debug.Assert(((IntPtr)sd.m_handle) != IntPtr.Zero, "Stream is disposed.");
     System.Runtime.InteropServices.GCHandle handle = (System.Runtime.InteropServices.GCHandle)(sd.m_handle);
     return((StreamAsIStream)(handle.Target));
 }
        /// <summary>
        /// Read a NSImage, covert the data and save it to the native pointer
        /// </summary>
        /// <typeparam name="T">The type of the data to covert the image pixel values to. e.g. "float" or "byte"</typeparam>
        /// <param name="image">The input image</param>
        /// <param name="dest">The native pointer where the image pixels values will be saved to.</param>
        /// <param name="inputHeight">The height of the image, must match the height requirement for the tensor</param>
        /// <param name="inputWidth">The width of the image, must match the width requirement for the tensor</param>
        /// <param name="inputMean">The mean value, it will be subtracted from the input image pixel values</param>
        /// <param name="scale">The scale, after mean is subtracted, the scale will be used to multiply the pixel values</param>
        /// <param name="flipUpSideDown">If true, the image needs to be flipped up side down</param>
        /// <param name="swapBR">If true, will flip the Blue channel with the Red. e.g. If false, the tensor's color channel order will be RGB. If true, the tensor's color channle order will be BGR </param>
        public static void ReadImageToTensor <T>(
            NSImage image,
            IntPtr dest,
            int inputHeight     = -1,
            int inputWidth      = -1,
            float inputMean     = 0.0f,
            float scale         = 1.0f,
            bool flipUpSideDown = false,
            bool swapBR         = false)
            where T : struct
        {
            if (flipUpSideDown)
            {
                throw new NotImplementedException("Flip Up Side Down is Not implemented");
            }
            NSImage resized;

            if (inputHeight > 0 || inputWidth > 0)
            {
                resized = new NSImage(new CGSize(inputWidth, inputHeight));
                resized.LockFocus();
                image.DrawInRect(new CGRect(0, 0, inputWidth, inputHeight), CGRect.Empty, NSCompositingOperation.SourceOver, 1.0f);
                resized.UnlockFocus();
            }
            else
            {
                resized = image;
            }

            int[]   intValues   = new int[(int)(resized.Size.Width * resized.Size.Height)];
            float[] floatValues = new float[(int)(resized.Size.Width * resized.Size.Height * 3)];
            System.Runtime.InteropServices.GCHandle handle = System.Runtime.InteropServices.GCHandle.Alloc(intValues, System.Runtime.InteropServices.GCHandleType.Pinned);
            using (CGImage cgimage = resized.CGImage)
                using (CGColorSpace cspace = CGColorSpace.CreateDeviceRGB())
                    using (CGBitmapContext context = new CGBitmapContext(
                               handle.AddrOfPinnedObject(),
                               (nint)resized.Size.Width,
                               (nint)resized.Size.Height,
                               8,
                               (nint)resized.Size.Width * 4,
                               cspace,
                               CGImageAlphaInfo.PremultipliedLast
                               ))
                    {
                        context.DrawImage(new CGRect(new CGPoint(), resized.Size), cgimage);
                    }
            handle.Free();
            if (swapBR)
            {
                for (int i = 0; i < intValues.Length; ++i)
                {
                    int val = intValues[i];
                    floatValues[i * 3 + 0] = ((val & 0xFF) - inputMean) * scale;
                    floatValues[i * 3 + 1] = (((val >> 8) & 0xFF) - inputMean) * scale;
                    floatValues[i * 3 + 2] = (((val >> 16) & 0xFF) - inputMean) * scale;
                }
            }
            else
            {
                for (int i = 0; i < intValues.Length; ++i)
                {
                    int val = intValues[i];
                    floatValues[i * 3 + 0] = (((val >> 16) & 0xFF) - inputMean) * scale;
                    floatValues[i * 3 + 1] = (((val >> 8) & 0xFF) - inputMean) * scale;
                    floatValues[i * 3 + 2] = ((val & 0xFF) - inputMean) * scale;
                }
            }

            if (typeof(T) == typeof(float))
            {
                Marshal.Copy(floatValues, 0, dest, floatValues.Length);
            }
            else if (typeof(T) == typeof(byte))
            {
                //copy float to bytes
                byte[] byteValues = new byte[floatValues.Length];
                for (int i = 0; i < floatValues.Length; i++)
                {
                    byteValues[i] = (byte)floatValues[i];
                }
                Marshal.Copy(byteValues, 0, dest, byteValues.Length);
            }
            else
            {
                throw new NotImplementedException(String.Format("Destination data type {0} is not supported.", typeof(T).ToString()));
            }
            if (resized != image)
            {
                resized.Dispose();
            }
        }
Exemple #42
0
 public CPhyEntity(NativePointer self)
 {
     mCoreObject = self;
     mWeakHandle = System.Runtime.InteropServices.GCHandle.Alloc(this, System.Runtime.InteropServices.GCHandleType.WeakTrackResurrection);
     SDK_PhyEntity_SetCSharpHandle(CoreObject, System.Runtime.InteropServices.GCHandle.ToIntPtr(mWeakHandle));
 }
Exemple #43
0
 public GCHandleProxy(System.Runtime.InteropServices.GCHandle gcHandle)
 {
     gch = gcHandle;
 }
Exemple #44
0
        /// <summary>
        /// Read the image file into a Tensorflow tensor
        /// </summary>
        /// <typeparam name="T">The tensor data type, e.g. float</typeparam>
        /// <param name="fileName">The name of the image file</param>
        /// <param name="inputHeight">The height of the input tensor. If zero or negative, will use the image height from the file</param>
        /// <param name="inputWidth">The width of the input tensor. If zero or negative, will use the image width from the file</param>
        /// <param name="inputMean">The input mean, will be subtracted from the image pixel value</param>
        /// <param name="scale">The optional scale, after input means is substracted, the pixel value will multiply with the scale to produce the tensor value</param>
        /// <param name="flipUpSideDown">If true, the image will be flipped upside down</param>
        /// <param name="swapBR">If true, the blue and red channels will be swapped</param>
        /// <returns>The tensorflow tensor.</returns>
        public static Tensor ReadTensorFromImageFile <T>(
            String fileName,
            int inputHeight     = -1,
            int inputWidth      = -1,
            float inputMean     = 0.0f,
            float scale         = 1.0f,
            bool flipUpSideDown = false,
            bool swapBR         = false) where T : struct
        {
#if __ANDROID__
            return(NativeReadTensorFromImageFile <T>(fileName, inputHeight, inputWidth, inputMean, scale,
                                                     flipUpSideDown, swapBR));
#elif __IOS__
            UIImage image = new UIImage(fileName);
            if (inputHeight > 0 || inputWidth > 0)
            {
                UIImage resized = image.Scale(new CGSize(inputWidth, inputHeight));
                image.Dispose();
                image = resized;
            }
            int[]   intValues   = new int[(int)(image.Size.Width * image.Size.Height)];
            float[] floatValues = new float[(int)(image.Size.Width * image.Size.Height * 3)];
            System.Runtime.InteropServices.GCHandle handle = System.Runtime.InteropServices.GCHandle.Alloc(intValues, System.Runtime.InteropServices.GCHandleType.Pinned);
            using (CGImage cgimage = image.CGImage)
                using (CGColorSpace cspace = CGColorSpace.CreateDeviceRGB())
                    using (CGBitmapContext context = new CGBitmapContext(
                               handle.AddrOfPinnedObject(),
                               (nint)image.Size.Width,
                               (nint)image.Size.Height,
                               8,
                               (nint)image.Size.Width * 4,
                               cspace,
                               CGImageAlphaInfo.PremultipliedLast
                               ))
                    {
                        context.DrawImage(new CGRect(new CGPoint(), image.Size), cgimage);
                    }
            handle.Free();

            for (int i = 0; i < intValues.Length; ++i)
            {
                int val = intValues[i];
                floatValues[i * 3 + 0] = (((val >> 16) & 0xFF) - inputMean) * scale;
                floatValues[i * 3 + 1] = (((val >> 8) & 0xFF) - inputMean) * scale;
                floatValues[i * 3 + 2] = ((val & 0xFF) - inputMean) * scale;
            }

            Tensor t = new Tensor(DataType.Float, new int[] { 1, (int)image.Size.Height, (int)image.Size.Width, 3 });
            System.Runtime.InteropServices.Marshal.Copy(floatValues, 0, t.DataPointer, floatValues.Length);
            return(t);
#else
            FileInfo fi        = new FileInfo(fileName);
            String   extension = fi.Extension.ToLower();

            //Use tensorflow to decode the following image formats
            if ((typeof(T) == typeof(float))
                &&
                (extension.Equals(".jpeg") ||
                 extension.Equals(".jpg") ||
                 extension.Equals(".png") ||
                 extension.Equals(".gif")))
            {
                return(DecodeImageToTensor32F3C(fileName, inputHeight, inputWidth, inputMean, scale, flipUpSideDown, swapBR));
            }
            else
            {
                return(NativeReadTensorFromImageFile <T>(fileName, inputHeight, inputWidth, inputMean, scale,
                                                         flipUpSideDown, swapBR));
            }
#endif
        }
Exemple #45
0
        public static Tensor ReadTensorFromImageFile(String fileName, int inputHeight = -1, int inputWidth = -1, float inputMean = 0.0f, float scale = 1.0f, Status status = null)
        {
#if __ANDROID__
            Android.Graphics.Bitmap bmp = BitmapFactory.DecodeFile(fileName);

            if (inputHeight > 0 || inputWidth > 0)
            {
                Bitmap resized = Bitmap.CreateScaledBitmap(bmp, inputWidth, inputHeight, false);
                bmp.Dispose();
                bmp = resized;
            }
            int[]   intValues   = new int[bmp.Width * bmp.Height];
            float[] floatValues = new float[bmp.Width * bmp.Height * 3];
            bmp.GetPixels(intValues, 0, bmp.Width, 0, 0, bmp.Width, bmp.Height);
            for (int i = 0; i < intValues.Length; ++i)
            {
                int val = intValues[i];
                floatValues[i * 3 + 0] = (((val >> 16) & 0xFF) - inputMean) * scale;
                floatValues[i * 3 + 1] = (((val >> 8) & 0xFF) - inputMean) * scale;
                floatValues[i * 3 + 2] = ((val & 0xFF) - inputMean) * scale;
            }

            Tensor t = new Tensor(DataType.Float, new int[] { 1, bmp.Height, bmp.Width, 3 });
            System.Runtime.InteropServices.Marshal.Copy(floatValues, 0, t.DataPointer, floatValues.Length);
            return(t);
#elif __IOS__
            UIImage image = new UIImage("surfers.jpg");
            if (inputHeight > 0 || inputWidth > 0)
            {
                UIImage resized = image.Scale(new CGSize(inputWidth, inputHeight));
                image.Dispose();
                image = resized;
            }
            int[]   intValues   = new int[(int)(image.Size.Width * image.Size.Height)];
            float[] floatValues = new float[(int)(image.Size.Width * image.Size.Height * 3)];
            System.Runtime.InteropServices.GCHandle handle = System.Runtime.InteropServices.GCHandle.Alloc(intValues, System.Runtime.InteropServices.GCHandleType.Pinned);
            using (CGImage cgimage = image.CGImage)
                using (CGColorSpace cspace = CGColorSpace.CreateDeviceRGB())
                    using (CGBitmapContext context = new CGBitmapContext(
                               handle.AddrOfPinnedObject(),
                               (nint)image.Size.Width,
                               (nint)image.Size.Height,
                               8,
                               (nint)image.Size.Width * 4,
                               cspace,
                               CGImageAlphaInfo.PremultipliedLast
                               ))
                    {
                        context.DrawImage(new CGRect(new CGPoint(), image.Size), cgimage);
                    }
            handle.Free();

            for (int i = 0; i < intValues.Length; ++i)
            {
                int val = intValues[i];
                floatValues[i * 3 + 0] = (((val >> 16) & 0xFF) - inputMean) * scale;
                floatValues[i * 3 + 1] = (((val >> 8) & 0xFF) - inputMean) * scale;
                floatValues[i * 3 + 2] = ((val & 0xFF) - inputMean) * scale;
            }

            Tensor t = new Tensor(DataType.Float, new int[] { 1, (int)image.Size.Height, (int)image.Size.Width, 3 });
            System.Runtime.InteropServices.Marshal.Copy(floatValues, 0, t.DataPointer, floatValues.Length);
            return(t);
#else
            using (StatusChecker checker = new StatusChecker(status))
            {
                var       graph = new Graph();
                Operation input = graph.Placeholder(DataType.String);

                Operation jpegDecoder = graph.DecodeJpeg(input, 3);                    //dimension 3

                Operation floatCaster = graph.Cast(jpegDecoder, DstT: DataType.Float); //cast to float

                Tensor    axis         = new Tensor(0);
                Operation axisOp       = graph.Const(axis, axis.Type, opName: "axis");
                Operation dimsExpander = graph.ExpandDims(floatCaster, axisOp); //turn it to dimension [1,3]

                Operation resized;
                bool      resizeRequired = (inputHeight > 0) && (inputWidth > 0);
                if (resizeRequired)
                {
                    Tensor    size   = new Tensor(new int[] { inputHeight, inputWidth }); // new size;
                    Operation sizeOp = graph.Const(size, size.Type, opName: "size");
                    resized = graph.ResizeBilinear(dimsExpander, sizeOp);                 //resize image
                }
                else
                {
                    resized = dimsExpander;
                }

                Tensor    mean        = new Tensor(inputMean);
                Operation meanOp      = graph.Const(mean, mean.Type, opName: "mean");
                Operation substracted = graph.Sub(resized, meanOp);

                Tensor    scaleTensor = new Tensor(scale);
                Operation scaleOp     = graph.Const(scaleTensor, scaleTensor.Type, opName: "scale");
                Operation scaled      = graph.Mul(substracted, scaleOp);

                //Operation scaled = graph.
                Session  session      = new Session(graph);
                Tensor   imageTensor  = Tensor.FromString(File.ReadAllBytes(fileName), status);
                Tensor[] imageResults = session.Run(new Output[] { input }, new Tensor[] { imageTensor },
                                                    new Output[] { scaled });
                return(imageResults[0]);
            }
#endif
        }
Exemple #46
0
 public static IntPtr ToIntPtr(GCHandle value)
 {
     return((IntPtr)value);
 }
Exemple #47
0
        private void CreateWindow(string className)
        {
            if (className == null)
            {
                throw new Exception("class_name is null");
            }
            if (className == String.Empty)
            {
                throw new Exception("class_name is empty");
            }

            _wndProcDelegate = CustomWndProc;

            gcHandle = System.Runtime.InteropServices.GCHandle.Alloc(_wndProcDelegate);

            WNDCLASS windClass = new WNDCLASS
            {
                cbClsExtra    = 0,
                cbWndExtra    = 0,
                hbrBackground = IntPtr.Zero,
                hCursor       = IntPtr.Zero,
                hIcon         = IntPtr.Zero,
                lpfnWndProc   = Marshal.GetFunctionPointerForDelegate(_wndProcDelegate),
                lpszClassName = className,
                lpszMenuName  = null,
                style         = 0
            };

            ushort classAtom = User32.RegisterClassW(ref windClass);

            int lastError = Marshal.GetLastWin32Error();

            if (classAtom == 0 && lastError != ERROR_CLASS_ALREADY_EXISTS)
            {
                throw new Exception("Could not register window class");
            }


            var owner = User32.GetWindow(_parentHandle, GetWindowCommands.GW_OWNER);

            _handle = User32.CreateWindowEx(
                (int)(WindowExStyles.WS_EX_LEFT | WindowExStyles.WS_EX_LTRREADING | WindowExStyles.WS_EX_LAYERED | WindowExStyles.WS_EX_TOOLWINDOW | WindowExStyles.WS_EX_RIGHTSCROLLBAR | WindowExStyles.WS_EX_NOACTIVATE | WindowExStyles.WS_EX_TRANSPARENT),
                new IntPtr(classAtom),
                className,
                //-(WindowStyles.WS_VISIBLE | WindowStyles.WS_MINIMIZE | WindowStyles.WS_CHILDWINDOW | WindowStyles.WS_CLIPCHILDREN | WindowStyles.WS_DISABLED | WindowStyles.WS_POPUP),
                (WindowStyles.WS_POPUP | WindowStyles.WS_VISIBLE | WindowStyles.WS_CLIPSIBLINGS | WindowStyles.WS_CLIPCHILDREN),
                0, 0, 0, 0, owner, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero);

            if (_handle == IntPtr.Zero)
            {
                return;
            }

            //const UInt32 extendedStyle = (UInt32)(
            //	WindowExStyles.WS_EX_LEFT |
            //	WindowExStyles.WS_EX_LTRREADING |
            //	WindowExStyles.WS_EX_RIGHTSCROLLBAR |
            //	WindowExStyles.WS_EX_TOOLWINDOW);

            //const UInt32 style = (UInt32)(
            //	WindowStyles.WS_CLIPSIBLINGS |
            //	WindowStyles.WS_CLIPCHILDREN |
            //	WindowStyles.WS_POPUP);

            //// Create window
            //_handle = User32.CreateWindowExW(
            //	extendedStyle,
            //	className,
            //	className,
            //	style,
            //	0,
            //	0,
            //	0,
            //	0,
            //	IntPtr.Zero,
            //	IntPtr.Zero,
            //	IntPtr.Zero,
            //	IntPtr.Zero
            //);

            //if (_handle == IntPtr.Zero)
            //{
            //	return;
            //}

            //uint styles = User32.GetWindowLong(_handle, GetWindowLongFlags.GWL_EXSTYLE);
            //styles = styles | (int)WindowExStyles.WS_EX_LAYERED | (int)WindowExStyles.WS_EX_NOACTIVATE | (int)WindowExStyles.WS_EX_TRANSPARENT;
            //User32.SetWindowLong(_handle, GetWindowLongFlags.GWL_EXSTYLE, styles);
        }
Exemple #48
0
        /// <summary>
        /// Read a NSImage, covert the data and save it to the native pointer
        /// </summary>
        /// <typeparam name="T">The type of the data to covert the image pixel values to. e.g. "float" or "byte"</typeparam>
        /// <param name="image">The input image</param>
        /// <param name="dest">The native pointer where the image pixels values will be saved to.</param>
        /// <param name="inputHeight">The height of the image, must match the height requirement for the tensor</param>
        /// <param name="inputWidth">The width of the image, must match the width requirement for the tensor</param>
        /// <param name="inputMean">The mean value, it will be subtracted from the input image pixel values</param>
        /// <param name="scale">The scale, after mean is subtracted, the scale will be used to multiply the pixel values</param>
        /// <param name="flipUpSideDown">If true, the image needs to be flipped up side down</param>
        /// <param name="swapBR">If true, will flip the Blue channel with the Red. e.g. If false, the tensor's color channel order will be RGB. If true, the tensor's color channle order will be BGR </param>
        /// <returns>The number of bytes written.</returns>
        public static int ReadImageToTensor <T>(
            NSImage image,
            IntPtr dest,
            int inputHeight     = -1,
            int inputWidth      = -1,
            float inputMean     = 0.0f,
            float scale         = 1.0f,
            bool flipUpSideDown = false,
            bool swapBR         = false)
            where T : struct
        {
            if (inputHeight <= 0)
            {
                inputHeight = (int)image.Size.Height;
            }
            if (inputWidth <= 0)
            {
                inputWidth = (int)image.Size.Width;
            }

            int[] intValues = new int[inputWidth * inputHeight];

            System.Runtime.InteropServices.GCHandle handle = System.Runtime.InteropServices.GCHandle.Alloc(intValues, System.Runtime.InteropServices.GCHandleType.Pinned);
            using (CGImage cgimage = image.CGImage)
                using (CGColorSpace cspace = CGColorSpace.CreateDeviceRGB())
                    using (CGBitmapContext context = new CGBitmapContext(
                               handle.AddrOfPinnedObject(),
                               inputWidth,
                               inputHeight,
                               8,
                               inputWidth * 4,
                               cspace,
                               CGImageAlphaInfo.PremultipliedLast
                               ))
                    {
                        context.DrawImage(new CGRect(new CGPoint(), new CGSize(inputWidth, inputHeight)), cgimage);
                    }

            int bytesWritten = 0;

            if (typeof(T) == typeof(float))
            {
                bytesWritten = Emgu.TF.Util.Toolbox.Pixel32ToPixelFloat(
                    handle.AddrOfPinnedObject(),
                    inputWidth,
                    inputHeight,
                    inputMean,
                    scale,
                    flipUpSideDown,
                    swapBR,
                    dest);
            }
            else if (typeof(T) == typeof(byte))
            {
                bytesWritten = Emgu.TF.Util.Toolbox.Pixel32ToPixelByte(
                    handle.AddrOfPinnedObject(),
                    inputWidth,
                    inputHeight,
                    inputMean,
                    scale,
                    flipUpSideDown,
                    swapBR,
                    dest);
            }
            else
            {
                throw new NotImplementedException(String.Format("Destination data type {0} is not supported.", typeof(T).ToString()));
            }
            handle.Free();
            return(bytesWritten);
        }
Exemple #49
0
 internal static EventProxyWrapper FromEPD(ref EventProxyDescriptor epd)
 {
     Debug.Assert(((IntPtr)epd.m_handle) != IntPtr.Zero, "Stream is disposed.");
     System.Runtime.InteropServices.GCHandle handle = (System.Runtime.InteropServices.GCHandle)(epd.m_handle);
     return((EventProxyWrapper)(handle.Target));
 }
Exemple #50
0
        /// <summary>
        /// Read an image file, covert the data and save it to the native pointer
        /// </summary>
        /// <typeparam name="T">The type of the data to covert the image pixel values to. e.g. "float" or "byte"</typeparam>
        /// <param name="fileName">The name of the image file</param>
        /// <param name="dest">The native pointer where the image pixels values will be saved to.</param>
        /// <param name="inputHeight">The height of the image, must match the height requirement for the tensor</param>
        /// <param name="inputWidth">The width of the image, must match the width requirement for the tensor</param>
        /// <param name="inputMean">The mean value, it will be substracted from the input image pixel values</param>
        /// <param name="scale">The scale, after mean is substracted, the scale will be used to multiply the pixel values</param>
        /// <param name="flipUpSideDown">If true, the image needs to be flipped up side down</param>
        /// <param name="swapBR">If true, will flip the Blue channel with the Red. e.g. If false, the tensor's color channel order will be RGB. If true, the tensor's color channle order will be BGR </param>
        public static void ReadImageFileToTensor <T>(
            String fileName,
            IntPtr dest,
            int inputHeight     = -1,
            int inputWidth      = -1,
            float inputMean     = 0.0f,
            float scale         = 1.0f,
            bool flipUpSideDown = false,
            bool swapBR         = false)
            where T : struct
        {
            if (!File.Exists(fileName))
            {
                throw new FileNotFoundException(String.Format("File {0} do not exist.", fileName));
            }

#if __ANDROID__
            Android.Graphics.Bitmap bmp = BitmapFactory.DecodeFile(fileName);
            if (inputHeight > 0 || inputWidth > 0)
            {
                Bitmap resized = Bitmap.CreateScaledBitmap(bmp, inputWidth, inputHeight, false);
                bmp.Dispose();
                bmp = resized;
            }

            if (flipUpSideDown)
            {
                Matrix matrix = new Matrix();
                matrix.PostScale(1, -1, bmp.Width / 2, bmp.Height / 2);
                Bitmap flipped = Bitmap.CreateBitmap(bmp, 0, 0, bmp.Width, bmp.Height, matrix, true);
                bmp.Dispose();
                bmp = flipped;
            }

            int[]   intValues   = new int[bmp.Width * bmp.Height];
            float[] floatValues = new float[bmp.Width * bmp.Height * 3];
            bmp.GetPixels(intValues, 0, bmp.Width, 0, 0, bmp.Width, bmp.Height);

            if (swapBR)
            {
                for (int i = 0; i < intValues.Length; ++i)
                {
                    int val = intValues[i];
                    floatValues[i * 3 + 0] = ((val & 0xFF) - inputMean) * scale;
                    floatValues[i * 3 + 1] = (((val >> 8) & 0xFF) - inputMean) * scale;
                    floatValues[i * 3 + 2] = (((val >> 16) & 0xFF) - inputMean) * scale;
                }
            }
            else
            {
                for (int i = 0; i < intValues.Length; ++i)
                {
                    int val = intValues[i];
                    floatValues[i * 3 + 0] = (((val >> 16) & 0xFF) - inputMean) * scale;
                    floatValues[i * 3 + 1] = (((val >> 8) & 0xFF) - inputMean) * scale;
                    floatValues[i * 3 + 2] = ((val & 0xFF) - inputMean) * scale;
                }
            }

            if (typeof(T) == typeof(float))
            {
                Marshal.Copy(floatValues, 0, dest, floatValues.Length);
            }
            else if (typeof(T) == typeof(byte))
            {
                //copy float to bytes
                byte[] byteValues = new byte[floatValues.Length];
                for (int i = 0; i < floatValues.Length; i++)
                {
                    byteValues[i] = (byte)floatValues[i];
                }
                Marshal.Copy(byteValues, 0, dest, byteValues.Length);
            }
            else
            {
                throw new NotImplementedException(String.Format("Destination data type {0} is not supported.", typeof(T).ToString()));
            }
#elif __IOS__
            if (flipUpSideDown)
            {
                throw new NotImplementedException("Flip Up Side Down is Not implemented");
            }

            UIImage image = new UIImage(fileName);
            if (inputHeight > 0 || inputWidth > 0)
            {
                UIImage resized = image.Scale(new CGSize(inputWidth, inputHeight));
                image.Dispose();
                image = resized;
            }
            int[]   intValues   = new int[(int)(image.Size.Width * image.Size.Height)];
            float[] floatValues = new float[(int)(image.Size.Width * image.Size.Height * 3)];
            System.Runtime.InteropServices.GCHandle handle = System.Runtime.InteropServices.GCHandle.Alloc(intValues, System.Runtime.InteropServices.GCHandleType.Pinned);
            using (CGImage cgimage = image.CGImage)
                using (CGColorSpace cspace = CGColorSpace.CreateDeviceRGB())
                    using (CGBitmapContext context = new CGBitmapContext(
                               handle.AddrOfPinnedObject(),
                               (nint)image.Size.Width,
                               (nint)image.Size.Height,
                               8,
                               (nint)image.Size.Width * 4,
                               cspace,
                               CGImageAlphaInfo.PremultipliedLast
                               ))
                    {
                        context.DrawImage(new CGRect(new CGPoint(), image.Size), cgimage);
                    }
            handle.Free();

            if (swapBR)
            {
                for (int i = 0; i < intValues.Length; ++i)
                {
                    int val = intValues[i];
                    floatValues[i * 3 + 0] = ((val & 0xFF) - inputMean) * scale;
                    floatValues[i * 3 + 1] = (((val >> 8) & 0xFF) - inputMean) * scale;
                    floatValues[i * 3 + 2] = (((val >> 16) & 0xFF) - inputMean) * scale;
                }
            }
            else
            {
                for (int i = 0; i < intValues.Length; ++i)
                {
                    int val = intValues[i];
                    floatValues[i * 3 + 0] = (((val >> 16) & 0xFF) - inputMean) * scale;
                    floatValues[i * 3 + 1] = (((val >> 8) & 0xFF) - inputMean) * scale;
                    floatValues[i * 3 + 2] = ((val & 0xFF) - inputMean) * scale;
                }
            }

            if (typeof(T) == typeof(float))
            {
                Marshal.Copy(floatValues, 0, dest, floatValues.Length);
            }
            else if (typeof(T) == typeof(byte))
            {
                //copy float to bytes
                byte[] byteValues = new byte[floatValues.Length];
                for (int i = 0; i < floatValues.Length; i++)
                {
                    byteValues[i] = (byte)floatValues[i];
                }
                Marshal.Copy(byteValues, 0, dest, byteValues.Length);
            }
            else
            {
                throw new NotImplementedException(String.Format("Destination data type {0} is not supported.", typeof(T).ToString()));
            }

            //System.Runtime.InteropServices.Marshal.Copy(floatValues, 0, dest, floatValues.Length);
#elif __UNIFIED__
            if (flipUpSideDown)
            {
                throw new NotImplementedException("Flip Up Side Down is Not implemented");
            }
            //if (swapBR)
            //    throw new NotImplementedException("swapBR is Not implemented");
            NSImage image = new NSImage(fileName);
            if (inputHeight > 0 || inputWidth > 0)
            {
                NSImage resized = new NSImage(new CGSize(inputWidth, inputHeight));
                resized.LockFocus();
                image.DrawInRect(new CGRect(0, 0, inputWidth, inputHeight), CGRect.Empty, NSCompositingOperation.SourceOver, 1.0f);
                resized.UnlockFocus();
                image.Dispose();
                image = resized;
            }
            int[]   intValues   = new int[(int)(image.Size.Width * image.Size.Height)];
            float[] floatValues = new float[(int)(image.Size.Width * image.Size.Height * 3)];
            System.Runtime.InteropServices.GCHandle handle = System.Runtime.InteropServices.GCHandle.Alloc(intValues, System.Runtime.InteropServices.GCHandleType.Pinned);
            using (CGImage cgimage = image.CGImage)
                using (CGColorSpace cspace = CGColorSpace.CreateDeviceRGB())
                    using (CGBitmapContext context = new CGBitmapContext(
                               handle.AddrOfPinnedObject(),
                               (nint)image.Size.Width,
                               (nint)image.Size.Height,
                               8,
                               (nint)image.Size.Width * 4,
                               cspace,
                               CGImageAlphaInfo.PremultipliedLast
                               ))
                    {
                        context.DrawImage(new CGRect(new CGPoint(), image.Size), cgimage);
                    }
            handle.Free();
            if (swapBR)
            {
                for (int i = 0; i < intValues.Length; ++i)
                {
                    int val = intValues[i];
                    floatValues[i * 3 + 0] = ((val & 0xFF) - inputMean) * scale;
                    floatValues[i * 3 + 1] = (((val >> 8) & 0xFF) - inputMean) * scale;
                    floatValues[i * 3 + 2] = (((val >> 16) & 0xFF) - inputMean) * scale;
                }
            }
            else
            {
                for (int i = 0; i < intValues.Length; ++i)
                {
                    int val = intValues[i];
                    floatValues[i * 3 + 0] = (((val >> 16) & 0xFF) - inputMean) * scale;
                    floatValues[i * 3 + 1] = (((val >> 8) & 0xFF) - inputMean) * scale;
                    floatValues[i * 3 + 2] = ((val & 0xFF) - inputMean) * scale;
                }
            }

            if (typeof(T) == typeof(float))
            {
                Marshal.Copy(floatValues, 0, dest, floatValues.Length);
            }
            else if (typeof(T) == typeof(byte))
            {
                //copy float to bytes
                byte[] byteValues = new byte[floatValues.Length];
                for (int i = 0; i < floatValues.Length; i++)
                {
                    byteValues[i] = (byte)floatValues[i];
                }
                Marshal.Copy(byteValues, 0, dest, byteValues.Length);
            }
            else
            {
                throw new NotImplementedException(String.Format("Destination data type {0} is not supported.", typeof(T).ToString()));
            }

            //System.Runtime.InteropServices.Marshal.Copy(floatValues, 0, dest, floatValues.Length);
#elif UNITY_EDITOR || UNITY_IOS || UNITY_ANDROID || UNITY_STANDALONE
            Texture2D texture = ReadTexture2DFromFile(fileName);
            ReadTensorFromTexture2D <T>(texture, dest, inputHeight, inputWidth, inputMean, scale, flipUpSideDown, false);
#else
            //if (System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(System.Runtime.InteropServices.OSPlatform.Windows))
            {
                //Read the file using Bitmap class
                System.Drawing.Bitmap bmp = new Bitmap(fileName);

                if (inputHeight > 0 || inputWidth > 0)
                {
                    //resize bmp
                    System.Drawing.Bitmap newBmp = new Bitmap(bmp, inputWidth, inputHeight);
                    bmp.Dispose();
                    bmp = newBmp;
                    //bmp.Save("tmp.png");
                }

                if (flipUpSideDown)
                {
                    bmp.RotateFlip(RotateFlipType.RotateNoneFlipY);
                }

                int bmpWidth  = bmp.Width;
                int bmpHeight = bmp.Height;
                System.Drawing.Imaging.BitmapData bd = new System.Drawing.Imaging.BitmapData();
                bmp.LockBits(
                    new Rectangle(0, 0, bmpWidth, bmpHeight),
                    System.Drawing.Imaging.ImageLockMode.ReadOnly,
                    System.Drawing.Imaging.PixelFormat.Format24bppRgb, bd);
                int stride = bd.Stride;

                byte[] byteValues = new byte[bmpHeight * stride];
                Marshal.Copy(bd.Scan0, byteValues, 0, byteValues.Length);
                bmp.UnlockBits(bd);

                if (typeof(T) == typeof(float))
                {
                    int     imageSize   = bmpWidth * bmpHeight;
                    float[] floatValues = new float[imageSize * 3];
                    if (swapBR)
                    {
                        int idx       = 0;
                        int rowOffset = 0;
                        for (int i = 0; i < bmpHeight; ++i)
                        {
                            int rowPtr = rowOffset;
                            for (int j = 0; j < bmpWidth; ++j)
                            {
                                float b = ((float)byteValues[rowPtr++] - inputMean) * scale;
                                float g = ((float)byteValues[rowPtr++] - inputMean) * scale;
                                float r = ((float)byteValues[rowPtr++] - inputMean) * scale;
                                floatValues[idx++] = r;
                                floatValues[idx++] = g;
                                floatValues[idx++] = b;
                            }
                            rowOffset += stride;
                        }
                    }
                    else
                    {
                        int idx       = 0;
                        int rowOffset = 0;
                        for (int i = 0; i < bmpHeight; ++i)
                        {
                            int rowPtr = rowOffset;
                            for (int j = 0; j < bmpWidth; ++j)
                            {
                                floatValues[idx++] = ((float)byteValues[rowPtr++] - inputMean) * scale;
                                floatValues[idx++] = ((float)byteValues[rowPtr++] - inputMean) * scale;
                                floatValues[idx++] = ((float)byteValues[rowPtr++] - inputMean) * scale;
                            }
                            rowOffset += stride;
                        }
                    }
                    Marshal.Copy(floatValues, 0, dest, floatValues.Length);
                }
                else if (typeof(T) == typeof(byte))
                {
                    int imageSize = bmp.Width * bmp.Height;
                    if (swapBR)
                    {
                        int idx = 0;
                        for (int i = 0; i < bmpHeight; ++i)
                        {
                            int offset = i * stride;
                            for (int j = 0; j < bmpWidth; ++j)
                            {
                                byte b = (byte)(((float)byteValues[offset++] - inputMean) * scale);
                                byte g = (byte)(((float)byteValues[offset++] - inputMean) * scale);
                                byte r = (byte)(((float)byteValues[offset++] - inputMean) * scale);
                                byteValues[idx++] = r;
                                byteValues[idx++] = g;
                                byteValues[idx++] = b;
                            }
                        }
                    }
                    else
                    {
                        int idx = 0;
                        for (int i = 0; i < bmpHeight; ++i)
                        {
                            int offset = i * stride;
                            for (int j = 0; j < bmpWidth * 3; ++j)
                            {
                                byteValues[idx++] = (byte)(((float)byteValues[offset++] - inputMean) * scale);
                            }
                        }
                    }
                    Marshal.Copy(byteValues, 0, dest, imageSize * 3);
                }
                else
                {
                    throw new NotImplementedException(String.Format("Destination data type {0} is not supported.", typeof(T).ToString()));
                }
            }

            /*
             * else //Unix
             * {
             *  //if (flipUpSideDown)
             *  //    throw new NotImplementedException("Flip Up Side Down is Not implemented");
             *
             *  throw new NotImplementedException("Not implemented");
             * }*/
#endif
        }
Exemple #51
0
        private void CreateWindow(string className)
        {
            if (className == null)
            {
                throw new Exception("class_name is null");
            }
            if (className == String.Empty)
            {
                throw new Exception("class_name is empty");
            }

            _wndProcDelegate = CustomWndProc;

            gcHandle = System.Runtime.InteropServices.GCHandle.Alloc(_wndProcDelegate);

            WNDCLASS windClass = new WNDCLASS
            {
                lpszClassName = className,
                lpfnWndProc   = Marshal.GetFunctionPointerForDelegate(_wndProcDelegate)
            };

            ushort classAtom = User32.RegisterClassW(ref windClass);

            int lastError = Marshal.GetLastWin32Error();

            if (classAtom == 0 && lastError != ERROR_CLASS_ALREADY_EXISTS)
            {
                throw new Exception("Could not register window class");
            }

            const UInt32 extendedStyle = (UInt32)(
                WindowExStyles.WS_EX_LEFT |
                WindowExStyles.WS_EX_LTRREADING |
                WindowExStyles.WS_EX_RIGHTSCROLLBAR |
                WindowExStyles.WS_EX_TOOLWINDOW);

            const UInt32 style = (UInt32)(
                WindowStyles.WS_CLIPSIBLINGS |
                WindowStyles.WS_CLIPCHILDREN |
                WindowStyles.WS_POPUP);

            // Create window
            _handle = User32.CreateWindowExW(
                extendedStyle,
                className,
                className,
                style,
                0,
                0,
                0,
                0,
                IntPtr.Zero,
                IntPtr.Zero,
                IntPtr.Zero,
                IntPtr.Zero
                );

            if (_handle == IntPtr.Zero)
            {
                return;
            }

            uint styles = User32.GetWindowLong(_handle, GetWindowLongFlags.GWL_EXSTYLE);

            styles = styles | (int)WindowExStyles.WS_EX_LAYERED | (int)WindowExStyles.WS_EX_NOACTIVATE | (int)WindowExStyles.WS_EX_TRANSPARENT;
            User32.SetWindowLong(_handle, GetWindowLongFlags.GWL_EXSTYLE, styles);
        }