Example #1
0
        public NDArrayList Invoke(NDArrayList outputs)
        {
            var paramKeys   = new List <string>();
            var paramValues = new List <string>();

            foreach (var data in _params)
            {
                paramKeys.Add(data.Key);
                paramValues.Add(data.Value);
            }

            var numInputs  = _inputNDArrays.Count;
            var numOutputs = outputs.Count;

            var      outputHandles   = outputs.Select(s => s.Handle).ToArray();
            var      outputsReceiver = IntPtr.Zero;
            GCHandle?gcHandle        = null;

            try
            {
                if (outputs.Count > 0)
                {
                    gcHandle        = GCHandle.Alloc(outputHandles, GCHandleType.Pinned);
                    outputsReceiver = gcHandle.Value.AddrOfPinnedObject();
                }

                NDArrayHandle[] outputsReceivers = { outputsReceiver };

                CheckCall(_LIB.MXImperativeInvoke(_handle, numInputs, _inputNDArrays.ToArray(), ref numOutputs,
                                                  ref outputsReceiver,
                                                  paramKeys.Count, paramKeys.ToArray(), paramValues.ToArray()));

                if (outputs.Count > 0)
                {
                    gcHandle?.Free();
                    return(outputs);
                }

                outputHandles = new NDArrayHandle[numOutputs];

                Marshal.Copy(outputsReceiver, outputHandles, 0, numOutputs);

                foreach (var outputHandle in outputHandles)
                {
                    outputs.Add(new NDArray(outputHandle));
                }

                gcHandle?.Free();
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                gcHandle?.Free();
            }

            return(outputs);
        }
Example #2
0
        public void Invoke(NDArrayList outputs)
        {
            var paramKeys   = new List <string>();
            var paramValues = new List <string>();

            foreach (var data in _Params)
            {
                paramKeys.Add(data.Key);
                paramValues.Add(data.Value);
            }

            var numInputs  = _InputNdarrays.Count;
            var numOutputs = outputs.Length;

            var      outputHandles   = outputs.Select(s => s.GetHandle()).ToArray();
            var      outputsReceiver = IntPtr.Zero;
            GCHandle?gcHandle        = null;

            try
            {
                if (outputs.Length > 0)
                {
                    gcHandle        = GCHandle.Alloc(outputHandles, GCHandleType.Pinned);
                    outputsReceiver = gcHandle.Value.AddrOfPinnedObject();
                }

                NDArrayHandle[] outputsReceivers = { outputsReceiver };

                Logging.CHECK_EQ(NativeMethods.MXImperativeInvoke(_Handle, numInputs, _InputNdarrays.ToArray(), ref numOutputs,
                                                                  ref outputsReceiver,
                                                                  paramKeys.Count, paramKeys.ToArray(), paramValues.ToArray()), NativeMethods.OK);

                if (outputs.Length > 0)
                {
                    gcHandle?.Free();
                    return;
                }

                outputHandles = new NDArrayHandle[numOutputs];

                Marshal.Copy(outputsReceiver, outputHandles, 0, numOutputs);

                foreach (var outputHandle in outputHandles)
                {
                    outputs.Add(new NDArray(outputHandle));
                }

                gcHandle?.Free();
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                gcHandle?.Free();
            }
        }
        int FreeCcw(Ccw *ccw)
        {
            lock (_lock)
            {
                // Shadow got resurrected by a call to QueryInterface from another thread
                if (ccw->RefCount != 0)
                {
                    return(ccw->RefCount);
                }

                var intPtr = new IntPtr(ccw);
                var type   = _backShadows[intPtr];
                _backShadows.Remove(intPtr);
                _shadows.Remove(type);
                Marshal.FreeHGlobal(intPtr);
                if (_shadows.Count == 0)
                {
                    _handle?.Free();
                    _handle = null;
                    try
                    {
                        Target.OnUnreferencedFromNative();
                    }
                    catch (Exception e)
                    {
                        MicroComRuntime.UnhandledException(Target, e);
                    }
                }
            }

            return(0);
        }
    // Update is called once per frame
    void Update()
    {
        // off-screen rendering
        var camtex = RenderTexture.GetTemporary (camWidth, camHeight, 24, RenderTextureFormat.Default, RenderTextureReadWrite.Default, 1);
        myCamera.targetTexture = camtex;
        myCamera.Render ();
        RenderTexture.active = camtex;

        tex.ReadPixels (new Rect (0, 0, camtex.width, camtex.height), 0, 0);
        tex.Apply ();

        // Convert texture to ptr
        texturePixels_       = tex.GetPixels32();
        texturePixelsHandle_ = GCHandle.Alloc(texturePixels_, GCHandleType.Pinned);
        texturePixelsPtr_    = texturePixelsHandle_.AddrOfPinnedObject();

        // Show a window
        fullWindow (windowName, displayNum, texturePixelsPtr_, camWidth, camHeight);

        texturePixelsHandle_.Free();

        RenderTexture.active = null;
        RenderTexture.ReleaseTemporary (camtex);
        myCamera.targetTexture = null;
    }
Example #5
0
 protected virtual void Dispose(bool disposing)
 {
     if (!_disposedValue)
     {
         // Note: We consider a handle to managed memory as an
         // unmanaged resource since it needs to be explicitly freed.
         _gcHandle?.Free();
         _disposedValue = true;
     }
 }
Example #6
0
    private void Cleanup(GCHandle[] argStrHandles, GCHandle argPtrsHandle,
                                       IntPtr gsInstancePtr)
    {
        for (int i = 0; i < argStrHandles.Length; i++)
                argStrHandles[i].Free();

            argPtrsHandle.Free();
            ExitAPI(gsInstancePtr);
            DeleteAPIInstance(gsInstancePtr);
    }
Example #7
0
        /// <summary>
        /// Called by vlc when the video format is needed. This method allocats the picture buffers for vlc and tells it to set the chroma to RV32
        /// </summary>
        /// <param name="userdata">The user data that will be given to the <see cref="LockVideo"/> callback. It contains the pointer to the buffer</param>
        /// <param name="chroma">The chroma</param>
        /// <param name="width">The visible width</param>
        /// <param name="height">The visible height</param>
        /// <param name="pitches">The buffer width</param>
        /// <param name="lines">The buffer height</param>
        /// <returns>The number of buffers allocated</returns>
        private uint VideoFormat(ref IntPtr userdata, IntPtr chroma, ref uint width, ref uint height, ref uint pitches, ref uint lines)
        {
            Debug.WriteLine("VideoFormat");
            ToFourCC("RV32", chroma);

            //Correct video width and height according to TrackInfo
            _size = new Size((int)width, (int)height);
            var md = _mediaPlayer.Media;

            foreach (MediaTrack track in md.Tracks)
            {
                if (track.TrackType == TrackType.Video)
                {
                    var trackInfo = track.Data;
                    if (trackInfo.Video.Width > 0 && trackInfo.Video.Height > 0)
                    {
                        width  = trackInfo.Video.Width;
                        height = trackInfo.Video.Height;
                        _size  = new Size((int)width, (int)height);
                        if (trackInfo.Video.SarDen != 0)
                        {
                            width = width * trackInfo.Video.SarNum / trackInfo.Video.SarDen;
                        }
                    }

                    break;
                }
            }

            pitches = this.GetAlignedDimension((uint)(width * 32) / 8, 32);
            lines   = this.GetAlignedDimension(height, 32);

            var b = new byte[width * height * 32];

            if (_imageData != null)
            {
                _imageData?.Free();
            }
            _imageData = GCHandle.Alloc(b, GCHandleType.Pinned);
            userdata   = ((GCHandle)_imageData).AddrOfPinnedObject();
            return(1);
        }
Example #8
0
        protected virtual void Dispose(bool disposing)
        {
            if (!_disposedValue)
            {
                if (disposing)
                {
                }

                _handle?.Free();
                _disposedValue = true;
            }
        }
Example #9
0
        /// <summary>
        ///     Initializes an output device.
        /// </summary>
        /// <param name="device">
        ///     The device to use... -1 = default device, 0 = no sound, 1 = first real output device.
        ///     <see cref="GetDeviceInfo" /> can be used to enumerate the available devices.
        /// </param>
        /// <param name="freq">Output sample rate. </param>
        /// <param name="configs">Configures of initialize Bass.</param>
        /// <param name="windowHandle">The application's main window... 0 = the desktop window (use this for console applications). </param>
        /// <param name="dSoundGuid">
        ///     Class identifier of the object to create, that will be used to initialize DirectSound... NULL
        ///     = use default.
        /// </param>
        /// <remarks>
        ///     This function must be successfully called before using any sample, stream or MOD music functions. The recording
        ///     functions may be used without having called this function.
        ///     <para />
        ///     Playback is not possible with the "no sound" device, but it does allow the use of "decoding channels", eg. to
        ///     decode files.
        ///     <para />
        ///     Simultaneously using multiple devices is supported in the Bass API via a context switching system; instead of there
        ///     being an extra "device" parameter in the function calls, the device to be used is set prior to calling the
        ///     functions. <see cref="SetDevice" /> is used to switch the current device. When successful,
        ///     <see cref="InitializeBass" /> automatically sets the current thread's device to the one that was just initialized.
        ///     <para />
        ///     When using the default device (device = -1), <see cref="GetDevice" /> can be used to find out which device it was
        ///     mapped to.
        /// </remarks>
        /// <exception cref="BassNotLoadedException">
        ///     Bass DLL not loaded, you must use <see cref="Interop.Core.Initialize" /> to
        ///     load Bass DLL first.
        /// </exception>
        /// <exception cref="BassErrorException">
        ///     Some error occur to call a Bass function, check the error code and error message
        ///     to get more error information.
        /// </exception>
        public static void InitializeBass(int device, uint freq, InitializationConfig configs, IntPtr windowHandle,
                                          Guid?dSoundGuid)
        {
            GCHandle?guidHandle = null;

            if (dSoundGuid != null)
            {
                guidHandle = GCHandle.Alloc(dSoundGuid.Value, GCHandleType.Pinned);
            }

            BassCoreModule.InitializeFunction.CheckResult(BassCoreModule.InitializeFunction.Delegate(device, freq, configs, windowHandle,
                                                                                                     guidHandle?.AddrOfPinnedObject() ?? IntPtr.Zero));

            guidHandle?.Free();
        }
Example #10
0
        /// <summary>
        /// Converts from an array of pixel data to a <see cref="Bitmap"/> image.
        /// </summary>
        /// <param name="width">The width of the bitmap.</param>
        /// <param name="pixelData">The values of individual pixels in ARGB format.</param>
        /// <returns>A bitmap image converted from the pixel data.</returns>
        public static Bitmap FromPixelData(int width, uint[] pixelData)
        {
            int      height       = pixelData.Length / width;
            GCHandle?gchPixelData = null;

            try
            {
                gchPixelData = GCHandle.Alloc(pixelData, GCHandleType.Pinned);
                return(new Bitmap(width, height, width * sizeof(uint), PixelFormat.Format32bppPArgb, gchPixelData.GetValueOrDefault().AddrOfPinnedObject()));
            }
            finally
            {
                gchPixelData?.Free();
            }
        }
Example #11
0
                /// <summary>
                /// Unloads the bank from the wwise engine
                /// </summary>
                /// <returns>The AKRESULT of unloading itself</returns>
                internal AKRESULT UnLoad()
                {
                    var result = AkSoundEngine.UnloadBank(BankID, BankDataPtr !.Value);

                    if (result != AKRESULT.AK_Success)
                    {
                        Debug.LogError("Failed to unload bank " + PublicID.ToString() + ": " + result.ToString());
                        return(result);
                    }

                    Memory?.Free();
                    Memory = null;

                    soundBanks.Remove(this);
                    return(result);
                }
Example #12
0
        /// <summary>
        ///
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="data"></param>
        /// <returns></returns>
        public static T FromByteArray <T>(byte[] data) where T : struct
        {
            GCHandle?gch = null;
            T        str;

            try
            {
                gch = GCHandle.Alloc(data, GCHandleType.Pinned);
                str = Marshal.PtrToStructure <T>(gch.Value.AddrOfPinnedObject());
            }
            finally
            {
                gch?.Free();
            }
            return(str);
        }
Example #13
0
        public void Invoke(List <NdArray> outputs)
        {
            List <string> inputKeys   = new List <string>();
            List <string> paramKeys   = new List <string>();
            List <string> paramValues = new List <string>();

            foreach (var data in _params)
            {
                paramKeys.Add(data.Key);
                paramValues.Add(data.Value);
            }
            foreach (var data in this._inputKeys)
            {
                inputKeys.Add(data);
            }
            int num_inputs  = _inputValues.Count;
            int num_outputs = outputs.Count;

            NdArrayHandle[] output_handles   = outputs.Select(s => s.get_handle()).ToArray();
            IntPtr          outputs_receiver = IntPtr.Zero;
            GCHandle?       gcHandle         = null;

            if (outputs.Count > 0)
            {
                gcHandle         = GCHandle.Alloc(output_handles, GCHandleType.Pinned);
                outputs_receiver = gcHandle.Value.AddrOfPinnedObject();
            }

            NativeMethods.MXImperativeInvoke(_handle, num_inputs, _inputValues.ToArray(), ref num_outputs, ref outputs_receiver,
                                             paramKeys.Count, paramKeys.ToArray(), paramValues.ToArray());

            if (outputs.Count > 0)
            {
                gcHandle?.Free();
                return;
            }
            output_handles = new IntPtr[num_outputs];

            Marshal.Copy(outputs_receiver, output_handles, 0, num_outputs);

            foreach (IntPtr outputHandle in output_handles)
            {
                outputs.Add(new NdArray(outputHandle));
            }
        }
Example #14
0
    public static int Main()
    {
        // The third element needs to be updated if Pinned is no longer the last value in the GCHandleType enum
        long[] invalidValues = { Int32.MinValue, -1, (long)(GCHandleType.Pinned + 1), Int32.MaxValue, UInt32.MaxValue, Int64.MaxValue };
        bool passed = true;

        for (int i = 0; i < invalidValues.Length; i++)
        {
            // GCHandle.Alloc internally casts the GCHandleType to a uint
            Console.WriteLine("Input: {0}, Converted to: {1}", invalidValues[i], (uint)invalidValues[i]);

            GCHandle gch = new GCHandle();
            try
            {
                gch = GCHandle.Alloc(new object(), (GCHandleType)(invalidValues[i]));
                Console.WriteLine("Failed");
                passed = false;
                gch.Free();
            }
            catch (ArgumentOutOfRangeException)
            {
                // caught the expected exception
                Console.WriteLine("Passed");
            }
            catch (Exception e)
            {
                Console.WriteLine("Caught unexpected exception");
                Console.WriteLine(e);
                passed = false;
            }

            Console.WriteLine();
        }

        if (passed)
        {
            Console.WriteLine("Test Passed");
            return 100;
        }

        Console.WriteLine("Test Failed");
        return 1;
    }
Example #15
0
        internal override Realm CreateRealm(RealmSchema schema)
        {
            var configuration = CreateNativeConfiguration();
            configuration.delete_if_migration_needed = ShouldDeleteIfMigrationNeeded;
            configuration.read_only = IsReadOnly;

            Migration migration = null;
            if (MigrationCallback != null)
            {
                migration = new Migration(this, schema);
                configuration.managed_migration_handle = GCHandle.ToIntPtr(migration.MigrationHandle);
            }

            GCHandle? shouldCompactHandle = null;
            if (ShouldCompactOnLaunch != null)
            {
                shouldCompactHandle = GCHandle.Alloc(ShouldCompactOnLaunch);
                configuration.managed_should_compact_delegate = GCHandle.ToIntPtr(shouldCompactHandle.Value);
            }

            var srPtr = IntPtr.Zero;
            try
            {
                srPtr = SharedRealmHandle.Open(configuration, schema, EncryptionKey);
            }
            catch (ManagedExceptionDuringMigrationException)
            {
                throw new AggregateException("Exception occurred in a Realm migration callback. See inner exception for more details.", migration?.MigrationException);
            }
            finally
            {
                migration?.ReleaseHandle();
                shouldCompactHandle?.Free();
            }

            var srHandle = new SharedRealmHandle(srPtr);
            if (IsDynamic && !schema.Any())
            {
                schema = srHandle.GetSchema();
            }

            return new Realm(srHandle, this, schema);
        }
Example #16
0
        /// <summary>
        /// Via <see cref="https://stackoverflow.com/a/25190648"/>
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="src"></param>
        /// <param name="func"></param>
        /// <returns></returns>
        public static T GetHash <T>(this SecureString src, Func <byte[], T> func)
        {
            var bstr = IntPtr.Zero;

            byte[]   workArray = null;
            GCHandle?handle    = null;

            try
            {
                /*** PLAINTEXT EXPOSURE BEGINS HERE ***/
                bstr = Marshal.SecureStringToBSTR(src);
                unsafe
                {
                    var bstrBytes = (byte *)bstr;
                    workArray = new byte[src.Length * 2];
                    handle    = GCHandle.Alloc(workArray, GCHandleType.Pinned);
                    for (var i = 0; i < workArray.Length; i++)
                    {
                        workArray[i] = *bstrBytes++;
                    }
                }

                return(func(workArray));
            }
            finally
            {
                if (workArray != null)
                {
                    for (var i = 0; i < workArray.Length; i++)
                    {
                        workArray[i] = 0;
                    }
                }

                handle?.Free();
                if (bstr != IntPtr.Zero)
                {
                    Marshal.ZeroFreeBSTR(bstr);
                }
                /*** PLAINTEXT EXPOSURE ENDS HERE ***/
            }
        }
        public static void SignFile(string certificateThumbprint, string pin, string containerName,
                                    CertificateStore store, string path, string timestampUrl, SignMode mode, Action <string> logger)
        {
            logger("Validating certificate thumbprint");
            if (certificateThumbprint?.Length != 40 || !ValidateThumbprint(certificateThumbprint))
            {
                throw new SigningException(
                          $"Invalid certificate thumbprint provided: {certificateThumbprint}. The thumbprint must be a valid SHA1 thumbprint - 40 characters long and consisting of only hexadecimal characters (0-9 and A-F)");
            }

            logger("Converting thumbprint to bytes");
            var binaryHash = StringToByteArray(certificateThumbprint);

            UnlockToken(containerName, Constants.CryptoProviderName, pin, logger);
            var systemStore = GetSystemStore(store);

            logger($"Opening system-level cryptographic store {systemStore}/{Constants.CryptoStoreName}");
            var certStore = NativeMethods.CertOpenStore(new IntPtr(Constants.CERT_STORE_PROV_SYSTEM),
                                                        Constants.DONT_CARE, IntPtr.Zero, systemStore, Constants.CryptoStoreName);

            if (certStore == IntPtr.Zero)
            {
                var errorResult = Marshal.GetHRForLastWin32Error();
                throw new SigningException($"Win32 error in CertOpenStore: {errorResult}",
                                           Marshal.GetExceptionForHR(errorResult));
            }

            GCHandle?h1 = null;
            GCHandle?h2 = null;

            try
            {
                var certificate = RetrieveCertificate(binaryHash, certStore, out h1, out h2, logger);
                SignFile(certificate, path, timestampUrl, mode, logger);
            }
            finally
            {
                h1?.Free();
                h2?.Free();
            }
        }
	void Start()
	{
		// テクスチャを生成
		texture_ = new Texture2D(10, 10, TextureFormat.RGB24, false);
		// テクスチャの拡大方法をニアレストネイバーに変更
		texture_.filterMode = FilterMode.Point;
		// Color32 型の配列としてテクスチャの参照をもらう
		pixels_ = texture_.GetPixels32();
		// GC されないようにする
		pixels_handle_ = GCHandle.Alloc(pixels_, GCHandleType.Pinned);
		// そのテクスチャのアドレスをもらう
		pixels_ptr_ = pixels_handle_.AddrOfPinnedObject();
		// スクリプトがアタッチされたオブジェクトのテクスチャをコレにする
		GetComponent<Renderer>().material.mainTexture = texture_;
		// ネイティブ側でテクスチャを生成
		create_check_texture(pixels_ptr_, texture_.width, texture_.height, 4);
		// セットして反映させる
		texture_.SetPixels32(pixels_);
		texture_.Apply(false, true);
		// GC 対象にする
		pixels_handle_.Free();
	}
	void Start()
	{
		var path = GetFilePath(imagePath);
		int width, height;
		if (!get_image_size(path, out width, out height)) {
			Debug.LogFormat("{0} was not found", path);
			return;
		}

		texture_ = new Texture2D(width, height, TextureFormat.RGB24, false);
		texture_.filterMode = FilterMode.Point;
		pixels_ = texture_.GetPixels32();
		pixels_handle_ = GCHandle.Alloc(pixels_, GCHandleType.Pinned);
		pixels_ptr_ = pixels_handle_.AddrOfPinnedObject();
		GetComponent<Renderer>().material.mainTexture = texture_;

		read_image(path, pixels_ptr_);

		texture_.SetPixels32(pixels_);
		texture_.Apply();
		pixels_handle_.Free();
	}
Example #20
0
        /// <summary>
        /// Converts from a bitmap image to an array of pixel data.
        /// </summary>
        /// <param name="bitmap">The bitmap image to be converted.</param>
        /// <returns>The pixel data contained in the image.</returns>
        public static uint[] ToPixelData(this Bitmap bitmap)
        {
            uint[]     pixelData    = new uint[bitmap.Width * bitmap.Height];
            BitmapData bitmapData   = null;
            GCHandle?  gchPixelData = null;

            try
            {
                gchPixelData = GCHandle.Alloc(pixelData, GCHandleType.Pinned);
                bitmapData   = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadOnly, PixelFormat.Format32bppPArgb);
                WindowsApi.CopyMemory(gchPixelData.GetValueOrDefault().AddrOfPinnedObject(), bitmapData.Scan0, (uint)(bitmapData.Stride * bitmapData.Height));
                return(pixelData);
            }
            finally
            {
                gchPixelData?.Free();

                if ((object)bitmapData != null)
                {
                    bitmap.UnlockBits(bitmapData);
                }
            }
        }
Example #21
0
 protected override void Dispose(bool disposing)
 {
     _handle?.Free();
     _handle = null;
 }
Example #22
0
 internal void ReleaseHandle()
 {
     _handle?.Free();
     _handle = null;
 }
 public void Dispose()
 {
     inHandle1.Free();
     inHandle2.Free();
     outHandle.Free();
 }
        // This overload is used in Mono to implement public constructors.
        private void Create(string pipeName, PipeDirection direction, int maxNumberOfServerInstances,
                            PipeTransmissionMode transmissionMode, PipeOptions options, int inBufferSize, int outBufferSize,
                            PipeSecurity?pipeSecurity, HandleInheritability inheritability, PipeAccessRights additionalAccessRights)
        {
            Debug.Assert(pipeName != null && pipeName.Length != 0, "fullPipeName is null or empty");
            Debug.Assert(direction >= PipeDirection.In && direction <= PipeDirection.InOut, "invalid pipe direction");
            Debug.Assert(inBufferSize >= 0, "inBufferSize is negative");
            Debug.Assert(outBufferSize >= 0, "outBufferSize is negative");
            Debug.Assert((maxNumberOfServerInstances >= 1 && maxNumberOfServerInstances <= 254) || (maxNumberOfServerInstances == MaxAllowedServerInstances), "maxNumberOfServerInstances is invalid");
            Debug.Assert(transmissionMode >= PipeTransmissionMode.Byte && transmissionMode <= PipeTransmissionMode.Message, "transmissionMode is out of range");

            string fullPipeName = Path.GetFullPath(@"\\.\pipe\" + pipeName);

            // Make sure the pipe name isn't one of our reserved names for anonymous pipes.
            if (string.Equals(fullPipeName, @"\\.\pipe\anonymous", StringComparison.OrdinalIgnoreCase))
            {
                throw new ArgumentOutOfRangeException(nameof(pipeName), SR.ArgumentOutOfRange_AnonymousReserved);
            }

            if (IsCurrentUserOnly)
            {
                Debug.Assert(pipeSecurity == null);

                using (WindowsIdentity currentIdentity = WindowsIdentity.GetCurrent())
                {
                    SecurityIdentifier identifier = currentIdentity.Owner !;

                    // Grant full control to the owner so multiple servers can be opened.
                    // Full control is the default per MSDN docs for CreateNamedPipe.
                    PipeAccessRule rule = new PipeAccessRule(identifier, PipeAccessRights.FullControl, AccessControlType.Allow);
                    pipeSecurity = new PipeSecurity();

                    pipeSecurity.AddAccessRule(rule);
                    pipeSecurity.SetOwner(identifier);
                }

                // PipeOptions.CurrentUserOnly is special since it doesn't match directly to a corresponding Win32 valid flag.
                // Remove it, while keeping others untouched since historically this has been used as a way to pass flags to CreateNamedPipe
                // that were not defined in the enumeration.
                options &= ~PipeOptions.CurrentUserOnly;
            }

            int openMode = ((int)direction) |
                           (maxNumberOfServerInstances == 1 ? Interop.Kernel32.FileOperations.FILE_FLAG_FIRST_PIPE_INSTANCE : 0) |
                           (int)options |
                           (int)additionalAccessRights;

            // We automatically set the ReadMode to match the TransmissionMode.
            int pipeModes = (int)transmissionMode << 2 | (int)transmissionMode << 1;

            // Convert -1 to 255 to match win32 (we asserted that it is between -1 and 254).
            if (maxNumberOfServerInstances == MaxAllowedServerInstances)
            {
                maxNumberOfServerInstances = 255;
            }

            GCHandle pinningHandle = default;

            try
            {
                Interop.Kernel32.SECURITY_ATTRIBUTES secAttrs = GetSecAttrs(inheritability, pipeSecurity, ref pinningHandle);
                SafePipeHandle handle = Interop.Kernel32.CreateNamedPipe(fullPipeName, openMode, pipeModes,
                                                                         maxNumberOfServerInstances, outBufferSize, inBufferSize, 0, ref secAttrs);

                if (handle.IsInvalid)
                {
                    throw Win32Marshal.GetExceptionForLastWin32Error();
                }

                InitializeHandle(handle, false, (options & PipeOptions.Asynchronous) != 0);
            }
            finally
            {
                if (pinningHandle.IsAllocated)
                {
                    pinningHandle.Free();
                }
            }
        }
	// Update is called once per frame
	void Update () {

        // 投影
        if (projection_flag)
        {

            // off-screen rendering
            //var camtex = RenderTexture.GetTemporary(proWidth, proHeight, 24, RenderTextureFormat.Default, RenderTextureReadWrite.Default, 1);
            //myProjector.targetTexture = camtex;
            //myProjector.Render();
            //RenderTexture.active = camtex;

            //tex.ReadPixels(new Rect(0, 0, camtex.width, camtex.height), 0, 0);
            //tex.Apply();

            RenderTexture.active = ProjectorImage;
            tex.ReadPixels(new Rect(0, 0, ProjectorImage.width, ProjectorImage.height), 0, 0);
            tex.Apply();

            // Convert texture to ptr
            texturePixels_ = tex.GetPixels32();
            texturePixelsHandle_ = GCHandle.Alloc(texturePixels_, GCHandleType.Pinned);
            texturePixelsPtr_ = texturePixelsHandle_.AddrOfPinnedObject();

            //投影するとゆがむので、(逆方向に)歪ませる
            undistort(texturePixelsPtr_, texturePixelsPtr_, proWidth, proHeight, procamManager.proj_K, procamManager.proj_dist);

            // Show a window
            fullWindow(windowName, displayNum, texturePixelsPtr_, proWidth, proHeight);
            //drawTextureFullWindow(window_, texturePixelsPtr_);

            texturePixelsHandle_.Free();

            //影画像のレンダリング
            Graphics.Blit(ProjectorImage, shadowImage, shadowMat);

            //RenderTexture.active = null;
            //RenderTexture.ReleaseTemporary(camtex);
            //myProjector.targetTexture = null;

            RenderTexture.active = null;
        }
	}
Example #26
0
        public static bool AreStreamsEqual(Stream left, Stream right)
        {
            if (null == left)
            {
                return(right == null);
            }
            if (null == right)
            {
                return(false);
            }

            if (!left.CanRead || !right.CanRead)
            {
                throw new NotSupportedException("The streams can't be read for comparison");
            }

            if (left.Length != right.Length)
            {
                return(false);
            }

            var length = (int)left.Length;

            // seek to beginning
            left.Position  = 0;
            right.Position = 0;

            // total bytes read
            int totalReadLeft  = 0;
            int totalReadRight = 0;

            // bytes read on this iteration
            int cbReadLeft  = 0;
            int cbReadRight = 0;

            // where to store the read data
            var leftBuffer  = new byte[512];
            var rightBuffer = new byte[512];

            // pin the left buffer
            GCHandle handleLeft = GCHandle.Alloc(leftBuffer, GCHandleType.Pinned);
            IntPtr   ptrLeft    = handleLeft.AddrOfPinnedObject();

            // pin the right buffer
            GCHandle handleRight = GCHandle.Alloc(rightBuffer, GCHandleType.Pinned);
            IntPtr   ptrRight    = handleRight.AddrOfPinnedObject();

            try {
                while (totalReadLeft < length)
                {
                    Assert.AreEqual(totalReadLeft, totalReadRight);

                    cbReadLeft  = left.Read(leftBuffer, 0, leftBuffer.Length);
                    cbReadRight = right.Read(rightBuffer, 0, rightBuffer.Length);

                    // verify the contents are an exact match
                    if (cbReadLeft != cbReadRight)
                    {
                        return(false);
                    }

                    if (!_MemCmp(ptrLeft, ptrRight, cbReadLeft))
                    {
                        return(false);
                    }

                    totalReadLeft  += cbReadLeft;
                    totalReadRight += cbReadRight;
                }

                Assert.AreEqual(cbReadLeft, cbReadRight);
                Assert.AreEqual(totalReadLeft, totalReadRight);
                Assert.AreEqual(length, totalReadLeft);

                return(true);
            }
            finally {
                handleLeft.Free();
                handleRight.Free();
            }
        }
 /// <summary>Remove monitor for key up event.</summary>
 public static void RemoveOnKeyUp()
 {
     _keyUpGcHandle?.Free();
     _keyUpGcHandle = null;
     removeOnKeyUp();
 }
 /// <summary>Remove monitor for left mouse up event.</summary>
 public static void RemoveOnLeftMouseUp()
 {
     _leftMouseUpGcHandle?.Free();
     _leftMouseUpGcHandle = null;
     removeOnLeftMouseUp();
 }
 /// <summary>
 /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
 /// </summary>
 public void Dispose()
 {
     pinnedArrayHandle?.Free();
 }
Example #30
0
 public void Dispose()
 {
     _virtualAfsHandle?.Free();
     GC.SuppressFinalize(this);
 }
    /// <summary>
    /// 自己証明書作成のメソッド本体
    ///   rawData が nullで、自己証明書を新規作成
    ///   rawDate を指定すると、既存の自己証明書の更新
    /// </summary>
    /// <param name="rawData">更新時の証明書バイナリーデータ</param>
    /// <param name="x500">組織名(CN="XXXXX")</param>
    /// <param name="startTime">開始日</param>
    /// <param name="endTime">終了日</param>
    /// <param name="insecurePassword">セキュア パスワード</param>
    /// <returns>証明書データ</returns>
    public static byte[] CreateSelfSignCertificatePfx(
        byte[] rawData,
        string x500,
        DateTime startTime,
        DateTime endTime,
        SecureString password)
    {
        byte[] pfxData;

        if (x500 == null)
        {
            x500 = "";
        }

        SystemTime startSystemTime = ToSystemTime(startTime);
        SystemTime endSystemTime = ToSystemTime(endTime);
        string containerName = Guid.NewGuid().ToString();

        GCHandle dataHandle = new GCHandle();
        IntPtr providerContext = IntPtr.Zero;
        IntPtr cryptKey = IntPtr.Zero;
        IntPtr certContext = IntPtr.Zero;
        IntPtr certStore = IntPtr.Zero;
        IntPtr storeCertContext = IntPtr.Zero;
        IntPtr passwordPtr = IntPtr.Zero;
        IntPtr callerFreeProvOrNCryptKey = IntPtr.Zero;

        // コード本体を制約された実行領域 (CER) として指定します。
        RuntimeHelpers.PrepareConstrainedRegions();
        try
        {
            if (password != null)
            {
                // アンマネージ COM タスク アロケーターから割り当てられたメモリ ブロックに、マネージ SecureString オブジェクトの内容をコピーします
                passwordPtr = Marshal.SecureStringToCoTaskMemUnicode(password);
            }

            if (rawData == null)
            {
                // 自己証明書の新規作成用にハンドル(HCRYPTPROV) を取得します(providerContext)

                // cryptographic service provider(CSP)内で キーコンテナに対するハンドル(HCRYPTPROV)を取得します
                Check(NativeMethods.CryptAcquireContextW(
                    out providerContext,
                    containerName,
                    //MS_ENHANCED_PROV,
                    null,
                    PROV_RSA_FULL,
                    CRYPT_NEWKEYSET));

                // ランダムな暗号化用のセッションキーか public/private のキーペアを生成します(HCRYPTKEY)
                Check(NativeMethods.CryptGenKey(
                    providerContext,
                    AT_KEYEXCHANGE,
                    //RSA2048BIT_KEY | CRYPT_EXPORTABLE, // 2048ビットへ変更、標準は1024ビット
                    RSA1024BIT_KEY | CRYPT_EXPORTABLE, // 2048ビットへ変更、標準は1024ビット
                    out cryptKey));
            }
            else
            {
                // 自己証明書の更新用にハンドル(HCRYPTPROV) を取得します(providerContext)

                // 証明書データ(PFX Blob)をインポートします
                CryptoApiBlob certBlob = new CryptoApiBlob();
                certBlob.DataLength = rawData.Length;               // 証明書データをPFX Blobへコピーします
                certBlob.Data = Marshal.AllocHGlobal(certBlob.DataLength);
                Marshal.Copy(rawData, 0, certBlob.Data, rawData.Length);
                Check(NativeMethods.PFXIsPFXBlob(ref certBlob));    // PFX Blobが正常かどうかを確認します
                certStore = NativeMethods.PFXImportCertStore(
                    ref certBlob,
                    passwordPtr,
                    CRYPT_EXPORTABLE | CRYPT_USER_KEYSET);
                Check(certStore != IntPtr.Zero);
                // 証明書を取得します
                certContext = NativeMethods.CertEnumCertificatesInStore(
                    certStore,
                    IntPtr.Zero);
                Check(certContext != IntPtr.Zero);

                // 証明書の private キーを含めて、キーコンテナに対するハンドル(HCRYPTPROV)を取得します
                IntPtr keySpec = IntPtr.Zero;
                Check(NativeMethods.CryptAcquireCertificatePrivateKey(
                    certContext,
                    0,
                    IntPtr.Zero,
                    out providerContext,
                    out keySpec,
                    out callerFreeProvOrNCryptKey));
                // 不要になったハンドルを解放
                Check(NativeMethods.CertCloseStore(certStore, 0));
                Check(NativeMethods.CertFreeCertificateContext(certContext));
                Marshal.FreeHGlobal(certBlob.Data);
                if (keySpec != IntPtr.Zero)
                    Marshal.FreeHGlobal(keySpec);
            }

            IntPtr errorStringPtr;
            int nameDataLength = 0;
            byte[] nameData;

            // errorStringPtr は、 x500 文字列に対するポインターを取得します。
            // この理由で、値を errorStringPtr へコピーするまではピン止めする必要があります
            dataHandle = GCHandle.Alloc(x500, GCHandleType.Pinned);

            // X.500 文字列を エンコードされた証明書名へ変換します
            if (!NativeMethods.CertStrToNameW(
                X509_ASN_ENCODING | PKCS_7_ASN_ENCODING,
                dataHandle.AddrOfPinnedObject(),
                CERT_X500_NAME_STR,
                IntPtr.Zero,
                null,
                ref nameDataLength,
                out errorStringPtr))
            {
                string error = Marshal.PtrToStringUni(errorStringPtr);
                throw new ArgumentException(error);
            }

            nameData = new byte[nameDataLength];

            if (!NativeMethods.CertStrToNameW(
                X509_ASN_ENCODING | PKCS_7_ASN_ENCODING,
                dataHandle.AddrOfPinnedObject(),
                CERT_X500_NAME_STR,
                IntPtr.Zero,
                nameData,
                ref nameDataLength,
                out errorStringPtr))
            {
                string error = Marshal.PtrToStringUni(errorStringPtr);
                throw new ArgumentException(error);
            }

            dataHandle.Free();

            dataHandle = GCHandle.Alloc(nameData, GCHandleType.Pinned);
            CryptoApiBlob nameBlob = new CryptoApiBlob(
                nameData.Length,
                dataHandle.AddrOfPinnedObject());

            // 暗号化キー情報
            CryptKeyProviderInformation kpi = new CryptKeyProviderInformation();
            kpi.ContainerName = containerName;
            kpi.ProviderType = PROV_RSA_FULL;
            kpi.KeySpec = AT_KEYEXCHANGE;

            // 自己証明書を作成し、CERT_CONTEXT 構造体のポインター(証明書)を返します。
            // HCRYPTPROV か、NCryptOpenKey を使用した NCRYPT_KEY_HANDLE
            certContext = NativeMethods.CertCreateSelfSignCertificate(
                providerContext,
                ref nameBlob,
                0,
                ref kpi,
                IntPtr.Zero, // default = SHA1RSA
                ref startSystemTime,
                ref endSystemTime,
                IntPtr.Zero);
            Check(certContext != IntPtr.Zero);
            dataHandle.Free();

            // 指定した CSP を使って証明書ストアを開きます
            certStore = NativeMethods.CertOpenStore(
                sz_CERT_STORE_PROV_MEMORY,
                0,
                IntPtr.Zero,
                CERT_STORE_CREATE_NEW_FLAG,
                IntPtr.Zero);
            Check(certStore != IntPtr.Zero);

            // 証明書コンテキストを証明書ストアへ追加します
            Check(NativeMethods.CertAddCertificateContextToStore(
                certStore,
                certContext,
                CERT_STORE_ADD_NEW,
                out storeCertContext));

            // 指定した証明書コンテキストへ拡張プロパティを設定します
            // この場合は暗号化キーです
            NativeMethods.CertSetCertificateContextProperty(
                storeCertContext,
                CERT_KEY_PROV_INFO_PROP_ID,
                0,
                ref kpi);

            CryptoApiBlob pfxBlob = new CryptoApiBlob();
            // 証明書をエクスポートします。参照された証明書ストアから関連付けられた private キーは、存在する場合にです
            // 1度目のエクスポートで、pfxBlob.DataLengthを取得します。
            // 2度目のエクスポートは、pfxBlob.Data を pfxDataにポインター経由で取得します。
            Check(NativeMethods.PFXExportCertStoreEx(
                certStore,
                ref pfxBlob,
                passwordPtr,
                IntPtr.Zero,
                EXPORT_PRIVATE_KEYS | REPORT_NO_PRIVATE_KEY | REPORT_NOT_ABLE_TO_EXPORT_PRIVATE_KEY));

            pfxData = new byte[pfxBlob.DataLength];
            dataHandle = GCHandle.Alloc(pfxData, GCHandleType.Pinned);
            pfxBlob.Data = dataHandle.AddrOfPinnedObject();
            Check(NativeMethods.PFXExportCertStoreEx(
                certStore,
                ref pfxBlob,
                passwordPtr,
                IntPtr.Zero,
                EXPORT_PRIVATE_KEYS | REPORT_NO_PRIVATE_KEY | REPORT_NOT_ABLE_TO_EXPORT_PRIVATE_KEY));
            dataHandle.Free();
        }
        catch (Exception e)
        {
            throw e;
        }
        finally
        {
            if (passwordPtr != IntPtr.Zero)
            {
                Marshal.ZeroFreeCoTaskMemUnicode(passwordPtr);
            }

            if (dataHandle.IsAllocated)
            {
                dataHandle.Free();
            }

            if (certContext != IntPtr.Zero)
            {
                // 証明書コンテキストを解放します
                NativeMethods.CertFreeCertificateContext(certContext);
            }

            if (storeCertContext != IntPtr.Zero)
            {
                // 証明書ストアコンテキストを解放します
                NativeMethods.CertFreeCertificateContext(storeCertContext);
            }

            if (certStore != IntPtr.Zero)
            {
                // 証明書ストアをクローズします
                NativeMethods.CertCloseStore(certStore, 0);
            }

            if (cryptKey != IntPtr.Zero)
            {
                // 暗号化キーを解放します
                NativeMethods.CryptDestroyKey(cryptKey);
            }

            if (providerContext != IntPtr.Zero)
            {
                // cryptographic service provider(CSP) を解放します
                NativeMethods.CryptReleaseContext(providerContext, 0);
                // 暗号化キーをコンテナから削除します
                NativeMethods.CryptAcquireContextW(
                    out providerContext,
                    containerName,
                    null,
                    PROV_RSA_FULL,
                    CRYPT_DELETEKEYSET);
            }

            if (callerFreeProvOrNCryptKey != IntPtr.Zero)
                Marshal.FreeHGlobal(callerFreeProvOrNCryptKey);
        }

        return pfxData;
    }
    // プロジェクタキャリブレーション
    void projectorCalibration()
    {
        // Kinectからカラーを取得
        tex = multiSourceManagerScript.GetColorTexture();

        // Convert texture to ptr
        texturePixels_ = tex.GetPixels32();
        texturePixelsHandle_ = GCHandle.Alloc(texturePixels_, GCHandleType.Pinned);
        texturePixelsPtr_ = texturePixelsHandle_.AddrOfPinnedObject();

        showKinectWindow(checkWindow, texturePixelsPtr_, multiSourceManagerScript.ColorWidth, multiSourceManagerScript.ColorHeight);

        string[] Filename_posi_cam = new string[g.all_bit];
        string[] Filename_nega_cam = new string[g.all_bit];
        // ポジパターン投影 & 撮影
        if (posi_count < g.all_bit)
        {
            // ポジパターン撮影結果を保存
            // 横縞
            if (posi_count < g.h_bit)
                Filename_posi_cam[posi_count] = "Calibration/GrayCodeImage/CaptureImage/CameraImg" + 0 + "_" + (posi_count + 1).ToString().PadLeft(2, '0') + "_" + 1 + ".bmp";
            // 縦縞
            else
                Filename_posi_cam[posi_count] = "Calibration/GrayCodeImage/CaptureImage/CameraImg" + 1 + "_" + (posi_count - g.h_bit + 1).ToString().PadLeft(2, '0') + "_" + 1 + ".bmp";
            // 保存
            saveTexture(Filename_posi_cam[posi_count], texturePixelsPtr_, multiSourceManagerScript.ColorWidth, multiSourceManagerScript.ColorHeight);

            posi_count++;

            // 投影
            if (posi_count < g.all_bit)
            {
                loadFullWindow(graycodeWindow, Filename_posi[posi_count], displayNum);
            }
            else
            {
                loadFullWindow(graycodeWindow, Filename_nega[0], displayNum);
            }
        }

        // ネガパターン投影 & 撮影
        else if (posi_count >= g.all_bit && nega_count < g.all_bit)
        {
            // ネガパターン撮影結果を保存
            // 横縞
            if (nega_count < g.h_bit)
                Filename_nega_cam[nega_count] = "Calibration/GrayCodeImage/CaptureImage/CameraImg" + 0 + "_" + (nega_count + 1).ToString().PadLeft(2, '0') + "_" + 0 + ".bmp";
            // 縦縞
            else
                Filename_nega_cam[nega_count] = "Calibration/GrayCodeImage/CaptureImage/CameraImg" + 1 + "_" + (nega_count - g.h_bit + 1).ToString().PadLeft(2, '0') + "_" + 0 + ".bmp";
            // 保存
            saveTexture(Filename_nega_cam[nega_count], texturePixelsPtr_, multiSourceManagerScript.ColorWidth, multiSourceManagerScript.ColorHeight);

            nega_count++;

            // 投影
            if (nega_count < g.all_bit)
            {
                loadFullWindow(graycodeWindow, Filename_nega[nega_count], displayNum);
            }
            else
            {
                // 投影終了
                calib_flag = false;

                closeWindow(graycodeWindow);
                closeWindow(checkWindow);
                print("グレイコード投影終了");

                make_thresh(proWidth, proHeight, camWidth, camHeight);
                print("2値化終了");

                int[] proPointx = new int[proWidth * proHeight];
                int[] proPointy = new int[proWidth * proHeight];
                int[] camPointx = new int[proWidth * proHeight];
                int[] camPointy = new int[proWidth * proHeight];
                int correspondNum = 0;
                makeCorrespondence(proWidth, proHeight, camWidth, camHeight, proPointx, proPointy, camPointx, camPointy, ref correspondNum);
                print("グレイコード終了");

                List<double> Point2dx = new List<double>();
                List<double> Point2dy = new List<double>();
                List<double> Point3dx = new List<double>();
                List<double> Point3dy = new List<double>();
                List<double> Point3dz = new List<double>();
                int correspoindNum2 = 0;

                // Kinectのカラー空間をカメラ空間へ変換
                calcColorPointToWorld(multiSourceManagerScript.GetDepthData(), multiSourceManagerScript.ColorWidth, multiSourceManagerScript.ColorHeight,
                                        camPointx, camPointy, proPointx, proPointy, correspondNum, ref Point2dx, ref Point2dy, ref Point3dx, ref Point3dy, ref Point3dz, ref correspoindNum2);

                double[] proPoint2dx = new double[correspoindNum2];
                double[] proPoint2dy = new double[correspoindNum2];
                double[] camPoint3dx = new double[correspoindNum2];
                double[] camPoint3dy = new double[correspoindNum2];
                double[] camPoint3dz = new double[correspoindNum2];
                proPoint2dx = Point2dx.ToArray();
                proPoint2dy = Point2dy.ToArray();
                camPoint3dx = Point3dx.ToArray();
                camPoint3dy = Point3dy.ToArray();
                camPoint3dz = Point3dz.ToArray();

                print("対応点数:"+correspoindNum2);

                double[] cameraMat = new double[16];
                double[] externalMat = new double[16];
                double result = 0;

                // プロジェクタキャリブレーション
                print("キャリブレーション実行");
                calcCalibration(proPoint2dx, proPoint2dy, camPoint3dx, camPoint3dy, camPoint3dz, correspoindNum2, proWidth, proHeight, cameraMat, externalMat, ref result);

                print("再投影誤差:"+result);

                // 透視投影変換行列を掛ける
                originalProjection.m00 = (float)cameraMat[0];
                originalProjection.m01 = (float)cameraMat[1];
                originalProjection.m02 = (float)cameraMat[2];
                originalProjection.m03 = (float)cameraMat[3];
                originalProjection.m10 = (float)cameraMat[4];
                originalProjection.m11 = (float)cameraMat[5];
                originalProjection.m12 = (float)cameraMat[6];
                originalProjection.m13 = (float)cameraMat[7];
                originalProjection.m20 = (float)cameraMat[8];
                originalProjection.m21 = (float)cameraMat[9];
                originalProjection.m22 = (float)cameraMat[10];
                originalProjection.m23 = (float)cameraMat[11];
                originalProjection.m30 = (float)cameraMat[12];
                originalProjection.m31 = (float)cameraMat[13];
                originalProjection.m32 = (float)cameraMat[14];
                originalProjection.m33 = (float)cameraMat[15];

                // set projection matrix
                myProjector.projectionMatrix = originalProjection;

                originalExternal.m00 = (float)externalMat[0];
                originalExternal.m01 = (float)externalMat[1];
                originalExternal.m02 = (float)externalMat[2];
                originalExternal.m03 = (float)externalMat[3];
                originalExternal.m10 = (float)externalMat[4];
                originalExternal.m11 = (float)externalMat[5];
                originalExternal.m12 = (float)externalMat[6];
                originalExternal.m13 = (float)externalMat[7];
                originalExternal.m20 = (float)externalMat[8];
                originalExternal.m21 = (float)externalMat[9];
                originalExternal.m22 = (float)externalMat[10];
                originalExternal.m23 = (float)externalMat[11];
                originalExternal.m30 = (float)externalMat[12];
                originalExternal.m31 = (float)externalMat[13];
                originalExternal.m32 = (float)externalMat[14];
                originalExternal.m33 = (float)externalMat[15];

                // set external matrix
                myProjector.worldToCameraMatrix = originalExternal;

                posi_count = 0;
                nega_count = 0;
            }
        }

        texturePixelsHandle_.Free();
    }
Example #33
0
 public static void Free(ref GCHandle gh)
 {
     gh.Free();
 }
Example #34
0
    public static byte[] CreateSelfSignCertificatePfx(
        string x500,
        DateTime startTime,
        DateTime endTime,
        SecureString password)
    {
        byte[] pfxData;

        if (x500 == null)
        {
            x500 = "";
        }

        SystemTime startSystemTime = ToSystemTime(startTime);
        SystemTime endSystemTime = ToSystemTime(endTime);
        string containerName = Guid.NewGuid().ToString();

        GCHandle dataHandle = new GCHandle();
        IntPtr providerContext = IntPtr.Zero;
        IntPtr cryptKey = IntPtr.Zero;
        IntPtr certContext = IntPtr.Zero;
        IntPtr certStore = IntPtr.Zero;
        IntPtr storeCertContext = IntPtr.Zero;
        IntPtr passwordPtr = IntPtr.Zero;
        RuntimeHelpers.PrepareConstrainedRegions();
        try
        {
            Check(NativeMethods.CryptAcquireContextW(
                out providerContext,
                containerName,
                null,
                1, // PROV_RSA_FULL
                8)); // CRYPT_NEWKEYSET

            Check(NativeMethods.CryptGenKey(
                providerContext,
                1, // AT_KEYEXCHANGE
                1, // CRYPT_EXPORTABLE
                out cryptKey));

            IntPtr errorStringPtr;
            int nameDataLength = 0;
            byte[] nameData;

            // errorStringPtr gets a pointer into the middle of the x500 string,
            // so x500 needs to be pinned until after we've copied the value
            // of errorStringPtr.
            dataHandle = GCHandle.Alloc(x500, GCHandleType.Pinned);

            if (!NativeMethods.CertStrToNameW(
                0x00010001, // X509_ASN_ENCODING | PKCS_7_ASN_ENCODING
                dataHandle.AddrOfPinnedObject(),
                3, // CERT_X500_NAME_STR = 3
                IntPtr.Zero,
                null,
                ref nameDataLength,
                out errorStringPtr))
            {
                string error = Marshal.PtrToStringUni(errorStringPtr);
                throw new ArgumentException(error);
            }

            nameData = new byte[nameDataLength];

            if (!NativeMethods.CertStrToNameW(
                0x00010001, // X509_ASN_ENCODING | PKCS_7_ASN_ENCODING
                dataHandle.AddrOfPinnedObject(),
                3, // CERT_X500_NAME_STR = 3
                IntPtr.Zero,
                nameData,
                ref nameDataLength,
                out errorStringPtr))
            {
                string error = Marshal.PtrToStringUni(errorStringPtr);
                throw new ArgumentException(error);
            }

            dataHandle.Free();

            dataHandle = GCHandle.Alloc(nameData, GCHandleType.Pinned);
            CryptoApiBlob nameBlob = new CryptoApiBlob(
                nameData.Length,
                dataHandle.AddrOfPinnedObject());

            CryptKeyProviderInformation kpi = new CryptKeyProviderInformation();
            kpi.ContainerName = containerName;
            kpi.ProviderType = 1; // PROV_RSA_FULL
            kpi.KeySpec = 1; // AT_KEYEXCHANGE

            certContext = NativeMethods.CertCreateSelfSignCertificate(
                providerContext,
                ref nameBlob,
                0,
                ref kpi,
                IntPtr.Zero, // default = SHA1RSA
                ref startSystemTime,
                ref endSystemTime,
                IntPtr.Zero);
            Check(certContext != IntPtr.Zero);
            dataHandle.Free();

            certStore = NativeMethods.CertOpenStore(
                "Memory", // sz_CERT_STORE_PROV_MEMORY
                0,
                IntPtr.Zero,
                0x2000, // CERT_STORE_CREATE_NEW_FLAG
                IntPtr.Zero);
            Check(certStore != IntPtr.Zero);

            Check(NativeMethods.CertAddCertificateContextToStore(
                certStore,
                certContext,
                1, // CERT_STORE_ADD_NEW
                out storeCertContext));

            NativeMethods.CertSetCertificateContextProperty(
                storeCertContext,
                2, // CERT_KEY_PROV_INFO_PROP_ID
                0,
                ref kpi);

            if (password != null)
            {
                passwordPtr = Marshal.SecureStringToCoTaskMemUnicode(password);
            }

            CryptoApiBlob pfxBlob = new CryptoApiBlob();
            Check(NativeMethods.PFXExportCertStoreEx(
                certStore,
                ref pfxBlob,
                passwordPtr,
                IntPtr.Zero,
                7)); // EXPORT_PRIVATE_KEYS | REPORT_NO_PRIVATE_KEY | REPORT_NOT_ABLE_TO_EXPORT_PRIVATE_KEY

            pfxData = new byte[pfxBlob.DataLength];
            dataHandle = GCHandle.Alloc(pfxData, GCHandleType.Pinned);
            pfxBlob.Data = dataHandle.AddrOfPinnedObject();
            Check(NativeMethods.PFXExportCertStoreEx(
                certStore,
                ref pfxBlob,
                passwordPtr,
                IntPtr.Zero,
                7)); // EXPORT_PRIVATE_KEYS | REPORT_NO_PRIVATE_KEY | REPORT_NOT_ABLE_TO_EXPORT_PRIVATE_KEY
            dataHandle.Free();
        }
        finally
        {
            if (passwordPtr != IntPtr.Zero)
            {
                Marshal.ZeroFreeCoTaskMemUnicode(passwordPtr);
            }

            if (dataHandle.IsAllocated)
            {
                dataHandle.Free();
            }

            if (certContext != IntPtr.Zero)
            {
                NativeMethods.CertFreeCertificateContext(certContext);
            }

            if (storeCertContext != IntPtr.Zero)
            {
                NativeMethods.CertFreeCertificateContext(storeCertContext);
            }

            if (certStore != IntPtr.Zero)
            {
                NativeMethods.CertCloseStore(certStore, 0);
            }

            if (cryptKey != IntPtr.Zero)
            {
                NativeMethods.CryptDestroyKey(cryptKey);
            }

            if (providerContext != IntPtr.Zero)
            {
                NativeMethods.CryptReleaseContext(providerContext, 0);
                NativeMethods.CryptAcquireContextW(
                    out providerContext,
                    containerName,
                    null,
                    1, // PROV_RSA_FULL
                    0x10); // CRYPT_DELETEKEYSET
            }
        }

        return pfxData;
    }
Example #35
0
 public void Dispose()
 {
     handle?.Free();
 }
Example #36
0
 public void Dispose()
 {
     GC.SuppressFinalize(this);
     _handle?.Free();
     _handle = null;
 }
Example #37
0
        public bool ConvertAllObjects(BulletFile file)
        {
            _shapeMap.Clear();
            _bodyMap.Clear();

            foreach (byte[] bvhData in file.Bvhs)
            {
                OptimizedBvh bvh = CreateOptimizedBvh();

                if ((file.Flags & FileFlags.DoublePrecision) != 0)
                {
                    throw new NotImplementedException();
                }
                else
                {
                    // QuantizedBvhData is parsed in C++, so we need to set pointers to actual values
                    GCHandle?contiguousNodes          = PinDataAtPointer(bvhData, QuantizedBvhFloatData.Offset("ContiguousNodesPtr"), file);
                    GCHandle?quantizedContiguousNodes = PinDataAtPointer(bvhData, QuantizedBvhFloatData.Offset("QuantizedContiguousNodesPtr"), file);
                    GCHandle?subTreeInfo = PinDataAtPointer(bvhData, QuantizedBvhFloatData.Offset("SubTreeInfoPtr"), file);

                    GCHandle bvhDataHandle    = GCHandle.Alloc(bvhData, GCHandleType.Pinned);
                    IntPtr   bvhDataPinnedPtr = bvhDataHandle.AddrOfPinnedObject();
                    bvh.DeSerializeFloat(bvhDataPinnedPtr);
                    bvhDataHandle.Free();

                    contiguousNodes?.Free();
                    quantizedContiguousNodes?.Free();
                    subTreeInfo?.Free();
                }

                foreach (KeyValuePair <long, byte[]> lib in file.LibPointers)
                {
                    if (lib.Value == bvhData)
                    {
                        _bvhMap.Add(lib.Key, bvh);
                        break;
                    }
                }
            }

            foreach (byte[] shapeData in file.CollisionShapes)
            {
                CollisionShape shape = ConvertCollisionShape(shapeData, file.LibPointers);
                if (shape != null)
                {
                    foreach (KeyValuePair <long, byte[]> lib in file.LibPointers)
                    {
                        if (lib.Value == shapeData)
                        {
                            _shapeMap.Add(lib.Key, shape);
                            break;
                        }
                    }

                    long namePtr = BulletReader.ToPtr(shapeData, CollisionShapeData.Offset("Name"));
                    if (namePtr != 0)
                    {
                        byte[] nameData = file.LibPointers[namePtr];
                        int    length   = Array.IndexOf(nameData, (byte)0);
                        string name     = System.Text.Encoding.ASCII.GetString(nameData, 0, length);
                        _objectNameMap.Add(shape, name);
                        _nameShapeMap.Add(name, shape);
                    }
                }
            }

            foreach (byte[] solverInfoData in file.DynamicsWorldInfo)
            {
                if ((file.Flags & FileFlags.DoublePrecision) != 0)
                {
                    //throw new NotImplementedException();
                }
                else
                {
                    //throw new NotImplementedException();
                }
            }

            foreach (byte[] bodyData in file.RigidBodies)
            {
                if ((file.Flags & FileFlags.DoublePrecision) != 0)
                {
                    ConvertRigidBodyDouble(bodyData, file.LibPointers);
                }
                else
                {
                    ConvertRigidBodyFloat(bodyData, file.LibPointers);
                }
            }

            foreach (byte[] colObjData in file.CollisionObjects)
            {
                using (var colObjStream = new MemoryStream(colObjData, false))
                {
                    using (var colObjReader = new BulletReader(colObjStream))
                    {
                        if ((file.Flags & FileFlags.DoublePrecision) != 0)
                        {
                            long           shapePtr       = colObjReader.ReadPtr(CollisionObjectDoubleData.Offset("CollisionShape"));
                            CollisionShape shape          = _shapeMap[shapePtr];
                            Math.Matrix    startTransform = colObjReader.ReadMatrixDouble(CollisionObjectDoubleData.Offset("WorldTransform"));
                            long           namePtr        = colObjReader.ReadPtr(CollisionObjectDoubleData.Offset("Name"));
                            string         name           = null;
                            if (namePtr != 0)
                            {
                                byte[] nameData = file.FindLibPointer(namePtr);
                                int    length   = Array.IndexOf(nameData, (byte)0);
                                name = System.Text.Encoding.ASCII.GetString(nameData, 0, length);
                            }
                            CollisionObject colObj = CreateCollisionObject(ref startTransform, shape, name);
                            _bodyMap.Add(colObjData, colObj);
                        }
                        else
                        {
                            long           shapePtr       = colObjReader.ReadPtr(CollisionObjectFloatData.Offset("CollisionShape"));
                            CollisionShape shape          = _shapeMap[shapePtr];
                            Math.Matrix    startTransform = colObjReader.ReadMatrix(CollisionObjectFloatData.Offset("WorldTransform"));
                            long           namePtr        = colObjReader.ReadPtr(CollisionObjectFloatData.Offset("Name"));
                            string         name           = null;
                            if (namePtr != 0)
                            {
                                byte[] nameData = file.FindLibPointer(namePtr);
                                int    length   = Array.IndexOf(nameData, (byte)0);
                                name = System.Text.Encoding.ASCII.GetString(nameData, 0, length);
                            }
                            CollisionObject colObj = CreateCollisionObject(ref startTransform, shape, name);
                            _bodyMap.Add(colObjData, colObj);
                        }
                    }
                }
            }

            foreach (byte[] constraintData in file.Constraints)
            {
                RigidBody a = null, b = null;

                long collisionObjectAPtr = BulletReader.ToPtr(constraintData, TypedConstraintFloatData.Offset("RigidBodyA"));
                if (collisionObjectAPtr != 0)
                {
                    if (!file.LibPointers.ContainsKey(collisionObjectAPtr))
                    {
                        a = TypedConstraint.GetFixedBody();
                    }
                    else
                    {
                        byte[] coData = file.LibPointers[collisionObjectAPtr];
                        a = RigidBody.Upcast(_bodyMap[coData]);
                        if (a == null)
                        {
                            a = TypedConstraint.GetFixedBody();
                        }
                    }
                }

                long collisionObjectBPtr = BulletReader.ToPtr(constraintData, TypedConstraintFloatData.Offset("RigidBodyB"));
                if (collisionObjectBPtr != 0)
                {
                    if (!file.LibPointers.ContainsKey(collisionObjectBPtr))
                    {
                        b = TypedConstraint.GetFixedBody();
                    }
                    else
                    {
                        byte[] coData = file.LibPointers[collisionObjectBPtr];
                        b = RigidBody.Upcast(_bodyMap[coData]);
                        if (b == null)
                        {
                            b = TypedConstraint.GetFixedBody();
                        }
                    }
                }

                if (a == null && b == null)
                {
                    continue;
                }

                if ((file.Flags & FileFlags.DoublePrecision) != 0)
                {
                    throw new NotImplementedException();
                }
                else
                {
                    ConvertConstraintFloat(a, b, constraintData, file.Version, file.LibPointers);
                }
            }

            return(true);
        }
Example #38
0
 public void TearDown()
 {
     pinnedBuffer?.Free();
     pinnedBuffer = null;
 }
 /// <summary>Remove monitor for right mouse up event.</summary>
 public static void RemoveOnRightMouseUp()
 {
     _rightMouseUpGcHandle?.Free();
     _rightMouseUpGcHandle = null;
     removeOnRightMouseUp();
 }
Example #40
0
    IEnumerator LoadFile()
    {
        ms_www = new WWW(m_bankPath);

        yield return ms_www;

        uint in_uInMemoryBankSize = 0;

        // Allocate an aligned buffer
        try
        {
            ms_pinnedArray = GCHandle.Alloc(ms_www.bytes, GCHandleType.Pinned);
            ms_pInMemoryBankPtr = ms_pinnedArray.AddrOfPinnedObject();
            in_uInMemoryBankSize = (uint)ms_www.bytes.Length;

            // Array inside the WWW object is not aligned. Allocate a new array for which we can guarantee the alignment.
            if( (ms_pInMemoryBankPtr.ToInt64() & AK_BANK_PLATFORM_DATA_ALIGNMENT_MASK) != 0 )
            {
                byte[] alignedBytes = new byte[ms_www.bytes.Length + AK_BANK_PLATFORM_DATA_ALIGNMENT];
                GCHandle new_pinnedArray = GCHandle.Alloc(alignedBytes, GCHandleType.Pinned);
                IntPtr new_pInMemoryBankPtr = new_pinnedArray.AddrOfPinnedObject();
                int alignedOffset = 0;

                // New array is not aligned, so we will need to use an offset inside it to align our data.
                if( (new_pInMemoryBankPtr.ToInt64() & AK_BANK_PLATFORM_DATA_ALIGNMENT_MASK) != 0 )
                {
                    Int64 alignedPtr = (new_pInMemoryBankPtr.ToInt64() + AK_BANK_PLATFORM_DATA_ALIGNMENT_MASK) & ~AK_BANK_PLATFORM_DATA_ALIGNMENT_MASK;
                    alignedOffset = (int)(alignedPtr - new_pInMemoryBankPtr.ToInt64());
                    new_pInMemoryBankPtr = new IntPtr(alignedPtr);
                }

                // Copy the bank's bytes in our new array, at the correct aligned offset.
                Array.Copy (ms_www.bytes, 0, alignedBytes, alignedOffset, ms_www.bytes.Length);

                ms_pInMemoryBankPtr = new_pInMemoryBankPtr;
                ms_pinnedArray.Free();
                ms_pinnedArray = new_pinnedArray;
            }
        }
        catch
        {
            yield break;
        }

        AKRESULT result = AkSoundEngine.LoadBank(ms_pInMemoryBankPtr, in_uInMemoryBankSize, out ms_bankID);
        if( result != AKRESULT.AK_Success )
        {
            Debug.LogError ("AkMemBankLoader: bank loading failed with result " + result.ToString ());
        }
    }
Example #41
0
        public void Dispose()
        {
            _handle?.Free();

            _handle = null;
        }