System.Runtime.InteropServices.GCHandle.Free()

Here are the examples of the csharp api System.Runtime.InteropServices.GCHandle.Free() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

1381 Examples 7

19 View Source File : DirectBitmap.cs
License : MIT License
Project Creator : altskop

public void Dispose()
        {
            if (Disposed) return;
            Disposed = true;
            Bitmap.Dispose();
            BitsHandle.Free();
        }

19 View Source File : Includer.cs
License : MIT License
Project Creator : amerkoleci

public unsafe void Dispose(Options options)
        {
#pragma warning disable CS8600, CS8625
            shaderc_compile_options_set_include_callbacks(options.Handle, null, null, null);
#pragma warning restore CS8600, CS8625
            foreach (var includeResultPtr in _shadercIncludeResults.Values)
                Free(includeResultPtr);
            _sourceToPath = new();
            _ptrToName = new();
            _shadercIncludeResults = new();
            if (_includerGCHandle.IsAllocated)
                _includerGCHandle.Free();
        }

19 View Source File : MemoryManager.cs
License : MIT License
Project Creator : Akaion

internal void WriteVirtualMemory<TStructure>(IntPtr baseAddress, TStructure structureToWrite) where TStructure : struct
        {
            var structureSize = Marshal.SizeOf<TStructure>();
            
            // Adjust the protection of the virtual memory region to ensure it has write privileges
            
            var originalProtectionType = ProtectVirtualMemory(baseAddress, structureSize, MemoryProtection.ReadWrite);

            var structureToWriteBufferHandle = GCHandle.Alloc(structureToWrite, GCHandleType.Pinned);
            
            if (!WriteProcessMemory(_processHandle, baseAddress, structureToWriteBufferHandle.AddrOfPinnedObject(), structureSize, IntPtr.Zero))
            {
                ExceptionHandler.ThrowWin32Exception("Failed to write into a region of virtual memory in the remote process");
            }
            
            // Restore the original protection of the virtual memory region
            
            ProtectVirtualMemory(baseAddress, structureSize, originalProtectionType);

            structureToWriteBufferHandle.Free();
        }

19 View Source File : 04-stream-add.cs
License : MIT License
Project Creator : altimesh

unsafe static void Main(string[] args)
        {
            int nStreams = 8;
            cudaStream_t[] streams = new cudaStream_t[nStreams];
            for (int k = 0; k < nStreams; ++k)
            {
                cuda.StreamCreate(out streams[k]);
            }

            int N = 1024 * 1024 * 32;
            float[] a = new float[N];
            float[] b = new float[N];

            for (int k = 0; k < N; ++k)
            {
                a[k] = (float)k;
                b[k] = 1.0F;
            }

            IntPtr d_a, d_b; // device pointers
            cuda.Malloc(out d_a, N * sizeof(float));
            cuda.Malloc(out d_b, N * sizeof(float));

            GCHandle handle_a = GCHandle.Alloc(a, GCHandleType.Pinned);
            GCHandle handle_b = GCHandle.Alloc(b, GCHandleType.Pinned);
            IntPtr h_a = handle_a.AddrOfPinnedObject();
            IntPtr h_b = handle_b.AddrOfPinnedObject();

            cuda.DeviceSynchronize();

            cuda.Memcpy(d_a, h_a, N * sizeof(float), cudaMemcpyKind.cudaMemcpyHostToDevice);
            cuda.Memcpy(d_b, h_b, N * sizeof(float), cudaMemcpyKind.cudaMemcpyHostToDevice);

            int slice = N / nStreams;

            dynamic wrapped = HybRunner.Cuda().Wrap(new Program());

            for (int k = 0; k < nStreams; ++k)
            {
                int start = k * slice;
                int stop = start + slice;
                wrapped.SetStream(streams[k]).Add(d_a, d_b, start, stop);
            }

            for (int k = 0; k < nStreams; ++k)
            {
                int start = k * slice;
                cuda.MemcpyAsync(h_a + start * sizeof(float), d_a + start * sizeof(float), slice * sizeof(float), cudaMemcpyKind.cudaMemcpyDeviceToHost, streams[k]);
            }

            for (int k = 0; k < nStreams; ++k)
            {
                cuda.StreamSynchronize(streams[k]);
                cuda.StreamDestroy(streams[k]);
            }

            for (int i = 0; i < N; ++i)
            {
                if (a[i] != (float)i + 1.0F)
                {
                    Console.Error.WriteLine("ERROR at {0} -- {1} != {2}", i, a[i], i + 1);
                    Environment.Exit(6); // abort
                }
            }

            handle_a.Free();
            handle_b.Free();
        }

19 View Source File : NotifyIconAdv.cs
License : MIT License
Project Creator : AlexGyver

public void LockReference(bool locked) {
          if (locked) {
            if (!referenceHandle.IsAllocated) {
              referenceHandle = GCHandle.Alloc(reference, GCHandleType.Normal);
              return;
            }
          } else {
            if (referenceHandle.IsAllocated)
              referenceHandle.Free();
          }
        }

19 View Source File : ProcessExtensions.cs
License : GNU General Public License v3.0
Project Creator : aglab2

static object ResolveToType(byte[] bytes, Type type)
        {
            object val;

            if (type == typeof(int))
            {
                val = BitConverter.ToInt32(bytes, 0);
            }
            else if (type == typeof(uint))
            {
                val = BitConverter.ToUInt32(bytes, 0);
            }
            else if (type == typeof(float))
            {
                val = BitConverter.ToSingle(bytes, 0);
            }
            else if (type == typeof(double))
            {
                val = BitConverter.ToDouble(bytes, 0);
            }
            else if (type == typeof(byte))
            {
                val = bytes[0];
            }
            else if (type == typeof(bool))
            {
                if (bytes == null)
                    val = false;
                else
                    val = (bytes[0] != 0);
            }
            else if (type == typeof(short))
            {
                val = BitConverter.ToInt16(bytes, 0);
            }
            else // probably a struct
            {
                var handle = GCHandle.Alloc(bytes, GCHandleType.Pinned);
                try
                {
                    val = Marshal.PtrToStructure(handle.AddrOfPinnedObject(), type);
                }
                finally
                {
                    handle.Free();
                }
            }

            return val;
        }

19 View Source File : Compiler.cs
License : MIT License
Project Creator : amerkoleci

public static ShaderBytecode CompressShaders(params ShaderBytecode[] shaderBytecodes)
        {
            Blob? blob = default;
            var shaderData = new ShaderData[shaderBytecodes.Length];
            var handles = new GCHandle[shaderBytecodes.Length];
            try
            {
                for (int i = 0; i < shaderBytecodes.Length; i++)
                {
                    handles[i] = GCHandle.Alloc(shaderBytecodes[i].Data, GCHandleType.Pinned);

                    shaderData[i] = new ShaderData
                    {
                        BytecodePtr = handles[i].AddrOfPinnedObject(),
                        BytecodeLength = shaderBytecodes[i].Data.Length
                    };
                }
                blob = CompressShaders(shaderBytecodes.Length, shaderData, 1);
            }
            finally
            {
                foreach (var handle in handles)
                {
                    handle.Free();
                }
            }

            if (blob == null)
            {
                return default;
            }

            return new ShaderBytecode(blob);
        }

19 View Source File : LogEventTests.Append.cs
License : MIT License
Project Creator : Abc-Arbitrage

[TearDown]
        public void Teardown()
        {
            _bufferHandler.Free();
        }

19 View Source File : NetworkInMessage.cs
License : MIT License
Project Creator : anderm

public virtual void ReadArray(byte[] data, uint arrayLength) {
    global::System.Runtime.InteropServices.GCHandle pinHandle_data = global::System.Runtime.InteropServices.GCHandle.Alloc(data, global::System.Runtime.InteropServices.GCHandleType.Pinned); try {
    {
      SharingClientPINVOKE.NetworkInMessage_ReadArray(swigCPtr, (global::System.IntPtr)pinHandle_data.AddrOfPinnedObject(), arrayLength);
    }
    } finally { pinHandle_data.Free(); }
  }

19 View Source File : OVRLipSync.cs
License : MIT License
Project Creator : absurd-joy

public static Result ProcessFrame(
    uint context, short[] audioBuffer, Frame frame, bool stereo = true)
    {
        if (IsInitialized() != Result.Success)
            return Result.Unknown;

        var dataType = stereo ? AudioDataType.S16_Stereo : AudioDataType.S16_Mono;
        var numSamples = (uint)(stereo ? audioBuffer.Length / 2 : audioBuffer.Length);
        var handle = GCHandle.Alloc(audioBuffer, GCHandleType.Pinned);
        var rc = ovrLipSyncDll_ProcessFrameEx(context,
                                              handle.AddrOfPinnedObject(), numSamples, dataType,
                                              ref frame.frameNumber, ref frame.frameDelay,
                                              frame.Visemes, frame.Visemes.Length,
                                              ref frame.laughterScore,
                                              null, 0
                                              );
        handle.Free();
        return (Result)rc;
    }

19 View Source File : Program.cs
License : MIT License
Project Creator : altimesh

static void Main(string[] args)
        {
            Complex[] h_signal = new Complex[SIGNAL_SIZE];
            for (int i = 0; i < SIGNAL_SIZE; ++i)
            {
                h_signal[i].x = (float)random.NextDouble();
                h_signal[i].y = 0.0F;
            }

            Complex[] h_filter_kernel = new Complex[FILTER_KERNEL_SIZE];
            for (int i = 0; i < FILTER_KERNEL_SIZE; ++i)
            {
                h_filter_kernel[i].x = (float)random.NextDouble();
                h_filter_kernel[i].y = 0.0F;
            }

            Complex[] h_padded_signal, h_padded_filter_kernel;
            int new_size = PadData(h_signal, out h_padded_signal, SIGNAL_SIZE, h_filter_kernel, out h_padded_filter_kernel, FILTER_KERNEL_SIZE);
            int mem_size = new_size * 2 * sizeof(float);

            // pin host data an copy to device
            GCHandle signalHandle = GCHandle.Alloc(h_padded_signal, GCHandleType.Pinned);
            GCHandle kernelHandle = GCHandle.Alloc(h_padded_filter_kernel, GCHandleType.Pinned);

            IntPtr d_signal;
            cuda.ERROR_CHECK(cuda.Malloc(out d_signal, mem_size));
            IntPtr d_filter_kernel;
            cuda.ERROR_CHECK(cuda.Malloc(out d_filter_kernel, mem_size));

            cuda.ERROR_CHECK(cuda.Memcpy(d_signal, signalHandle.AddrOfPinnedObject(), mem_size, cudaMemcpyKind.cudaMemcpyHostToDevice));
            cuda.ERROR_CHECK(cuda.Memcpy(d_filter_kernel, kernelHandle.AddrOfPinnedObject(), mem_size, cudaMemcpyKind.cudaMemcpyHostToDevice));


            cufftHandle plan;
            cufft_ERROR_CHECK(cufft.Plan1d(out plan, new_size, cufftType.CUFFT_C2C, 1));

            cufftHandle plan_adv;
            size_t workSize;
            long new_size_long = new_size;
            cufft_ERROR_CHECK(cufft.Create(out plan_adv));
            cufft_ERROR_CHECK(cufft.XtMakePlanMany(plan_adv, 1, new long[1] { new_size_long }, null, 1, 1, cudaDataType_t.CUDA_C_32F, null, 1, 1, cudaDataType_t.CUDA_C_32F, 1, out workSize, cudaDataType_t.CUDA_C_32F));

            cufft_ERROR_CHECK(cufft.ExecC2C(plan, d_signal, d_signal, -1));
            cufft_ERROR_CHECK(cufft.ExecC2C(plan_adv, d_filter_kernel, d_filter_kernel, -1));

            dynamic wrapped = HybRunner.Cuda().SetDistrib(32, 256).Wrap(new Program());
            wrapped.ComplexPointwiseMulAndScale(d_signal, d_filter_kernel, new_size, 1.0F / new_size);

            cuda.ERROR_CHECK(cuda.GetLastError());
            
            cufft_ERROR_CHECK(cufft.ExecC2C(plan, d_signal, d_signal, 1));

            cuda.ERROR_CHECK(cuda.Memcpy(signalHandle.AddrOfPinnedObject(), d_signal, mem_size, cudaMemcpyKind.cudaMemcpyDeviceToHost));
            
            Complex[] h_convolved_signal_ref = new Complex[SIGNAL_SIZE];
            Convolve(h_signal, SIGNAL_SIZE, h_filter_kernel, FILTER_KERNEL_SIZE, h_convolved_signal_ref);

            bool bResult = CompareL2(h_convolved_signal_ref, h_padded_signal, 1.0E-5F);

            cufft_ERROR_CHECK(cufft.Destroy(plan));
            cufft_ERROR_CHECK(cufft.Destroy(plan_adv));
            signalHandle.Free();
            kernelHandle.Free();
            cuda.ERROR_CHECK(cuda.Free(d_signal));
            cuda.ERROR_CHECK(cuda.Free(d_filter_kernel));

            if(bResult)
            {
                Console.Error.WriteLine("ERROR");
                Environment.Exit(6);
            }

            Console.Out.WriteLine("OK");
        }

19 View Source File : Program.cs
License : MIT License
Project Creator : altimesh

unsafe static void Main(string[] args)
        {
            int nStreams = 8;
            cudaStream_t[] streams = new cudaStream_t[nStreams];
            dynamic wrapped = HybRunner.Cuda().Wrap(new Program());
            for (int k = 0; k < nStreams; ++k)
            {
                cuda.StreamCreate(out streams[k]);
            }

            int N = 1024 * 1024 * 32;
            IntPtr d_a, d_b; // device pointers
            float[] a = new float[N];
            float[] b = new float[N];

            cuda.Malloc(out d_a, N * sizeof(float));
            cuda.Malloc(out d_b, N * sizeof(float));

            for(int k = 0; k < N; ++k)
            {
                a[k] = (float)k;
                b[k] = 1.0F;
            }

            GCHandle handle_a = GCHandle.Alloc(a, GCHandleType.Pinned);
            GCHandle handle_b = GCHandle.Alloc(b, GCHandleType.Pinned);
            IntPtr h_a = handle_a.AddrOfPinnedObject();
            IntPtr h_b = handle_b.AddrOfPinnedObject();

            int slice = N / nStreams;

            cuda.DeviceSynchronize();

            cuda.Memcpy(d_a, h_a, N * sizeof(float), cudaMemcpyKind.cudaMemcpyHostToDevice);
            cuda.Memcpy(d_b, h_b, N * sizeof(float), cudaMemcpyKind.cudaMemcpyHostToDevice);
            
            for (int k = 0; k < nStreams; ++k)
            {
                int start = k * slice;
                int stop = start + slice;
                wrapped.SetStream(streams[k]).Add(d_a, d_b, start, stop, 100);
            }

            for (int k = 0; k < nStreams; ++k)
            {
                int start = k * slice;
                cuda.MemcpyAsync(h_a + start * sizeof(float), d_a + start * sizeof(float), slice * sizeof(float), cudaMemcpyKind.cudaMemcpyDeviceToHost, streams[k]);
            }

            for (int k = 0; k < nStreams; ++k)
            {
                cuda.StreamSynchronize(streams[k]);
                cuda.StreamDestroy(streams[k]);
            }

            for(int k = 0; k < 10; ++k)
            {
                Console.WriteLine(a[k]);
            }

            handle_a.Free();
            handle_b.Free();
        }

19 View Source File : Z85.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

public static byte[] Encode(byte[] decoded)
		{
			int dataLen = decoded.Length;
			if (dataLen % 4 > 0)
			{
				throw new InvalidOperationException("decoded.Length must be divisible by 4");
			}
			int destLen = (Int32)(decoded.Length * 1.25);

			var data = GCHandle.Alloc(decoded, GCHandleType.Pinned);

            // the buffer dest must be one byte larger than destLen to accomodate the null termination character
			using (var dest = DispoIntPtr.Alloc(destLen + 1))
			{
				if (IntPtr.Zero == zmq.z85_encode(dest, data.AddrOfPinnedObject(), dataLen))
				{
					data.Free();
					throw new InvalidOperationException();
				}
				data.Free();

				var bytes = new byte[destLen];

				Marshal.Copy(dest, bytes, 0, destLen);

				return bytes;
			}
		}

19 View Source File : NPPIMage.cs
License : MIT License
Project Creator : altimesh

public static void Save(string path, IntPtr devicePtr, int width, int pitch, int height)
        {
            ushort[] arr = new ushort[height * width];
            var handle = GCHandle.Alloc(arr, GCHandleType.Pinned);
            cuda.ERROR_CHECK(cuda.Memcpy2D(handle.AddrOfPinnedObject(), width * sizeof(ushort), devicePtr, pitch, width * sizeof(ushort), height, cudaMemcpyKind.cudaMemcpyDeviceToHost));
            handle.Free();
            Bitmap bitmap = new Bitmap(width, height);
            int index = 0;
            for (int j = 0; j < height; ++j)
            {
                for (int i = 0; i < width; ++i, ++index)
                {
                    ushort pixel = arr[j * width + i];
                    bitmap.SetPixel(i, j, Color.FromArgb(pixel, pixel, pixel));
                }
            }
            bitmap.Save(path, ImageFormat.Png);
        }

19 View Source File : OvrWarpDX11Test.cs
License : MIT License
Project Creator : ab4d

[TestMethod]
		public void Session_SubmitFrame()
		{
			IntPtr sessionPtr = CreateSession();
			replacedert.AreNotEqual(IntPtr.Zero, sessionPtr);

			// Define field of view (This is used for both left and right eye).
			FovPort fieldOfView	= new FovPort();
			fieldOfView.DownTan	 = (float) Math.Tan(0.523598776); // 0.523598776 radians = 30 degrees.
			fieldOfView.UpTan	 = (float) Math.Tan(0.523598776); // 0.523598776 radians = 30 degrees.
			fieldOfView.LeftTan	 = (float) Math.Tan(0.785398163); // 0.785398163 radians = 45 degrees.
			fieldOfView.RightTan = (float) Math.Tan(0.785398163); // 0.785398163 radians = 45 degrees.

			EyeRenderDesc renderDescLeft  = OVR.GetRenderDesc(sessionPtr, EyeType.Left, fieldOfView);
			EyeRenderDesc renderDescRight = OVR.GetRenderDesc(sessionPtr, EyeType.Left, fieldOfView);

			var viewScaleDesc = new ViewScaleDesc();
		    viewScaleDesc.HmdToEyePose0 = renderDescLeft.HmdToEyePose;
            viewScaleDesc.HmdToEyePose1 = renderDescRight.HmdToEyePose;
			viewScaleDesc.HmdSpaceToWorldScaleInMeters = 1;

			// Determine texture size matching the field of view.
			Sizei sizeLeft  = OVR.GetFovTextureSize(sessionPtr, EyeType.Left, fieldOfView, 1.0f);
			Sizei sizeRight	= OVR.GetFovTextureSize(sessionPtr, EyeType.Right, fieldOfView, 1.0f);

			var hmdToEyeViewOffset	= new Vector3f[2];
			var poses = new Posef[2];
		    double sensorSampleTime;

			hmdToEyeViewOffset[0].X	= -0.1f;
			hmdToEyeViewOffset[1].X	= 0.1f;

			OVR.GetEyePoses(sessionPtr, 0, true, hmdToEyeViewOffset, ref poses, out sensorSampleTime);

			// Create a set of layers to submit.
			LayerEyeFov	layer	= new LayerEyeFov();
            layer.Header.Type = LayerType.EyeFov;

            Result result;

			using(TestEngine testEngine = CreateTestEngine(sessionPtr))
			{
				try
				{
					// Create a texture for the left eye.
					layer.ColorTextureLeft		 = CreateTextureSwapChain(sessionPtr, testEngine);
					layer.ViewportLeft.Position  = new Vector2i(0, 0);
					layer.ViewportLeft.Size	     = sizeLeft;
					layer.FovLeft                = fieldOfView;
					layer.RenderPoseLeft         = poses[0];

                    // Create a texture for the right eye.
					layer.ColorTextureRight		 = CreateTextureSwapChain(sessionPtr, testEngine);
					layer.ViewportRight.Position = new Vector2i(0, 0);
					layer.ViewportRight.Size	 = sizeLeft;
					layer.FovRight               = fieldOfView;
                    layer.RenderPoseRight        = poses[1];


                    // The created texture swap chain must be committed to the Oculus SDK, before using it in the
                    // call to ovr_SubmitFrame, otherwise ovr_SubmitFrame will fail.
                    result = OVR.CommitTextureSwapChain(sessionPtr, layer.ColorTextureLeft);
                    replacedert.IsTrue(result >= Result.Success);

                    result = OVR.CommitTextureSwapChain(sessionPtr, layer.ColorTextureRight);
					replacedert.IsTrue(result >= Result.Success);


                    // SubmitFrame requires pointer to an array of pointers to Layer objects
                    var layerPointers = new IntPtr[1];

                    GCHandle layerHandle = GCHandle.Alloc(layer, GCHandleType.Pinned);
                    GCHandle layerPointersHandle = GCHandle.Alloc(layerPointers, GCHandleType.Pinned);

				    layerPointers[0] = layerHandle.AddrOfPinnedObject();

                    result = OVR.SubmitFrame(sessionPtr, 0L, IntPtr.Zero, layerPointersHandle.AddrOfPinnedObject(), 1);
					replacedert.IsTrue(result >= Result.Success);

                    layerPointersHandle.Free();
                    layerHandle.Free();
                }
				finally
				{
                    if (layer.ColorTextureLeft != IntPtr.Zero)
                        OVR.DestroyTextureSwapChain(sessionPtr, layer.ColorTextureLeft);

                    if (layer.ColorTextureRight != IntPtr.Zero)
                        OVR.DestroyTextureSwapChain(sessionPtr, layer.ColorTextureRight);
				}
			}
		}

19 View Source File : NetworkClass.cs
License : GNU General Public License v2.0
Project Creator : AmanoTooko

private static ParseResult Parse(byte[] data)
        {
            GCHandle handle = GCHandle.Alloc(data, GCHandleType.Pinned);
            FFXIVMessageHeader head = (FFXIVMessageHeader)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(FFXIVMessageHeader));
            handle.Free();

            ParseResult result = new ParseResult();
            result.header = head;
            result.data = data;

            return result;
        }

19 View Source File : GCHandleHandler.cs
License : Apache License 2.0
Project Creator : airbus-cert

public void Dispose()
        {
            if (Handle != null)
                Handle.Free();
        }

19 View Source File : IncludeShadow.cs
License : MIT License
Project Creator : amerkoleci

public void Dispose()
            {
                if (_handle.IsAllocated)
                    _handle.Free();
            }

19 View Source File : UnityRemoteVideo.cs
License : MIT License
Project Creator : 734843327

void OnDestroy()
		{
			m_Session.SetCapturePixelData (false, IntPtr.Zero, IntPtr.Zero);

			m_pinnedYArray.Free ();
			m_pinnedUVArray.Free ();

		}

19 View Source File : AnchorDownloadRequest.cs
License : MIT License
Project Creator : anderm

public virtual bool GetData(byte[] data, int dataSize) {
    global::System.Runtime.InteropServices.GCHandle pinHandle_data = global::System.Runtime.InteropServices.GCHandle.Alloc(data, global::System.Runtime.InteropServices.GCHandleType.Pinned); try {
    {
      bool ret = SharingClientPINVOKE.AnchorDownloadRequest_GetData(swigCPtr, (global::System.IntPtr)pinHandle_data.AddrOfPinnedObject(), dataSize);
      return ret;
    }
    } finally { pinHandle_data.Free(); }
  }

19 View Source File : SpanHelper.cs
License : MIT License
Project Creator : Alan-FGR

[MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static unsafe void Copy<T>(ref Buffer<T> source, int sourceIndex, ref Array<T> target, int targetIndex, int count)
        {
            Validate<T, Buffer<T>, Array<T>>(ref source, sourceIndex, ref target, targetIndex, count);
            var arrayHandle = GCHandle.Alloc(target.Memory, GCHandleType.Pinned);
            var byteCount = count * Unsafe.SizeOf<T>();
            Buffer.MemoryCopy(
                source.Memory + sourceIndex * Unsafe.SizeOf<T>(),
                Unsafe.AsPointer(ref target[targetIndex]),
                byteCount, byteCount);
            arrayHandle.Free();
        }

19 View Source File : SpanHelper.cs
License : MIT License
Project Creator : Alan-FGR

[MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static unsafe void Copy<T>(ref Array<T> source, int sourceIndex, ref Buffer<T> target, int targetIndex, int count)
        {
            Validate<T, Array<T>, Buffer<T>>(ref source, sourceIndex, ref target, targetIndex, count);
            var arrayHandle = GCHandle.Alloc(source.Memory, GCHandleType.Pinned);
            var byteCount = count * Unsafe.SizeOf<T>();
            Buffer.MemoryCopy(
                Unsafe.AsPointer(ref source[sourceIndex]),
                target.Memory + targetIndex * Unsafe.SizeOf<T>(),
                byteCount, byteCount);
            arrayHandle.Free();
        }

19 View Source File : OvrWrap64.Common.cs
License : MIT License
Project Creator : ab4d

public override void CalcEyePoses(Posef headPose, Vector3f[] hmdToEyeOffset, ref Posef[] eyePoses)
        {
            if (eyePoses == null)
                throw new ArgumentNullException("eyePoses");

            if (eyePoses.Length != 2)
                throw new ArgumentException("eyePoses array should have 2 Posef items", "eyePoses");


            GCHandle posesHandle = GCHandle.Alloc(eyePoses, GCHandleType.Pinned);
            try
            {
                SafeNativeMethods.ovr_CalcEyePoses(headPose, hmdToEyeOffset, posesHandle.AddrOfPinnedObject());
            }
            finally
            {
                posesHandle.Free();
            }
        }

19 View Source File : VoiceServer.Events.Native.cs
License : MIT License
Project Creator : AlternateLife

private void DisposeNativeEvents()
        {
            NativeWrapper.UnregisterClientConnectedCallback();
            NativeWrapper.UnregisterClientConnectingCallback();
            NativeWrapper.UnregisterClientDisconnectedCallback();
            NativeWrapper.UnregisterClientRejectedCallback();
            
            NativeWrapper.UnregisterClientTalkingChangedCallback();
            NativeWrapper.UnregisterClientSpeakersMuteChangedCallback();
            NativeWrapper.UnregisterClientMicrophoneMuteChangedCallback();
            
            NativeWrapper.UnregisterLogMessageCallback();

            foreach (var handle in _garbageCollectorHandles)
            {
                handle.Free();
            }
        }

19 View Source File : OVROverlay.cs
License : MIT License
Project Creator : absurd-joy

private void DestroyLayer()
	{
		if (layerIndex != -1)
		{
			// Turn off the overlay if it was on.
			OVRPlugin.EnqueueSubmitLayer(true, false, false, IntPtr.Zero, IntPtr.Zero, -1, 0, OVRPose.idenreplacedy.ToPosef_Legacy(), Vector3.one.ToVector3f(), layerIndex, (OVRPlugin.OverlayShape)prevOverlayShape);
			instances[layerIndex] = null;
			layerIndex = -1;
		}

		if (layerIdPtr != IntPtr.Zero)
		{
			OVRPlugin.EnqueueDestroyLayer(layerIdPtr);
			layerIdPtr = IntPtr.Zero;
			layerIdHandle.Free();
			layerId = 0;
		}

		layerDesc = new OVRPlugin.LayerDesc();

		frameIndex = 0;
		prevFrameIndex = -1;
	}

19 View Source File : Program.cs
License : MIT License
Project Creator : altimesh

unsafe static void Main(string[] args)
        {
            int nStreams = 8;
            cudaStream_t[] streams = new cudaStream_t[nStreams];
            HybRunner[] runners = new HybRunner[nStreams];
            dynamic[] wrapped = new dynamic[nStreams];
            cudaDeviceProp prop;
            cuda.GetDeviceProperties(out prop, 0);
            for (int k = 0; k < nStreams; ++k)
            {
                cuda.StreamCreate(out streams[k]);

                runners[k] = HybRunner.Cuda("Streams_CUDA.dll", streams[k], CudaMarshaler.Instance).SetDistrib(16 * prop.multiProcessorCount, 128);
                wrapped[k] = runners[k].Wrap(new Program());
            }

            int N = 1024 * 1024 * 32;
            IntPtr d_a, d_b; // device pointers
            float[] a = new float[N];
            float[] b = new float[N];

            cuda.Malloc(out d_a, N * sizeof(float));
            cuda.Malloc(out d_b, N * sizeof(float));

            for(int k = 0; k < N; ++k)
            {
                a[k] = (float)k;
                b[k] = 1.0F;
            }

            GCHandle handle_a = GCHandle.Alloc(a, GCHandleType.Pinned);
            GCHandle handle_b = GCHandle.Alloc(b, GCHandleType.Pinned);
            IntPtr h_a = handle_a.AddrOfPinnedObject();
            IntPtr h_b = handle_b.AddrOfPinnedObject();

            int slice = N / nStreams;

            cuda.DeviceSynchronize();

            cuda.Memcpy(d_a, h_a, N * sizeof(float), cudaMemcpyKind.cudaMemcpyHostToDevice);
            cuda.Memcpy(d_b, h_b, N * sizeof(float), cudaMemcpyKind.cudaMemcpyHostToDevice);

            for (int k = 0; k < nStreams; ++k)
            {
                int start = k * slice;
                int stop = start + slice;
                wrapped[k].Add(d_a, d_b, start, stop, 100);
            }
            for (int k = 0; k < nStreams; ++k)
            {
                int start = k * slice;
                cuda.MemcpyAsync(h_a + start * sizeof(float), d_a + start * sizeof(float), slice * sizeof(float), cudaMemcpyKind.cudaMemcpyDeviceToHost, streams[k]);
            }

            for (int k = 0; k < nStreams; ++k)
            {
                cuda.StreamSynchronize(streams[k]);
                cuda.StreamDestroy(streams[k]);
            }

            for(int k = 0; k < 10; ++k)
            {
                Console.WriteLine(a[k]);
            }

            handle_a.Free();
            handle_b.Free();
        }

19 View Source File : NPPIMage.cs
License : MIT License
Project Creator : altimesh

public static NPPImage Load(string path, cudaStream_t stream)
        {
            NPPImage result = new NPPImage();
            byte[] rawData;
            if (Path.GetExtension(path).Contains("pgm"))
            {
                using (FileStream fs = new FileStream(path, FileMode.Open))
                {
                    using (TextReader tReader = new StreamReader(fs))
                    using (BinaryReader bReader = new BinaryReader(fs))
                    {
                        string formatLine = tReader.ReadLine(); // skip
                        string sizeLine = tReader.ReadLine();
                        string[] splitted = sizeLine.Split(' ');
                        result.width = int.Parse(splitted[0]);
                        result.height = int.Parse(splitted[1]);

                        string maxValueLine = tReader.ReadLine(); // skip
                        int pos = formatLine.Length + sizeLine.Length + maxValueLine.Length + 3;
                        fs.Seek(pos, SeekOrigin.Begin);

                        // TODO: optimize that part
                        rawData = bReader.ReadBytes((int)(fs.Length - pos));

                    }
                }
            }
            else if (Path.GetExtension(path).Contains("png"))
            {
                Bitmap image = Bitmap.FromFile(path) as Bitmap;
                result.width = image.Width;
                result.height = image.Height;
                rawData = new byte[result.width * result.height];
                int index = 0;
                for (int j = 0; j < result.height; ++j)
                {
                    for (int i = 0; i < result.width; ++i, ++index)
                    {
                        rawData[index] = image.GetPixel(i, j).R;
                    }
                }
            }
            else
            {
                throw new NotSupportedException("unsupported file format");
            }

            IntPtr deviceData;
            size_t p;
            cuda.ERROR_CHECK(cuda.MallocPitch(out deviceData, out p, result.width * sizeof(ushort), result.height));
            result.pitch = (int)p;

            result.hostData = new ushort[result.height * result.width];
            for (int j = 0; j < result.height; ++j)
            {
                for (int i = 0; i < result.width; ++i)
                {
                    result.hostData[j * result.width + i] = rawData[j * result.width + i];
                }
            }

            var handle = GCHandle.Alloc(result.hostData, GCHandleType.Pinned);
            cuda.ERROR_CHECK(cuda.Memcpy2DAsync(deviceData, p, handle.AddrOfPinnedObject(), result.width * sizeof(ushort), result.width * sizeof(ushort), result.height, cudaMemcpyKind.cudaMemcpyHostToDevice, stream));
            handle.Free();
            result.deviceData = deviceData;

            return result;
        }

19 View Source File : WindowMoved.cs
License : GNU General Public License v3.0
Project Creator : Adam-Wilkinson

public void RemoveTriggers()
        {
            if (_gcSafetyHandle.IsAllocated)
            {
                _gcSafetyHandle.Free();
            }
            WindowHooks.WinEventUnhook(_hook);
        }

19 View Source File : 03-malloc-add.cs
License : MIT License
Project Creator : altimesh

unsafe static void Main(string[] args)
        {
            int N = 1024 * 1024 * 32;
            float[] a = new float[N];
            float[] b = new float[N];

            for (int k = 0; k < N; ++k)
            {
                a[k] = (float)k;
                b[k] = 1.0F;
            }

            IntPtr d_a, d_b; //device pointer
            cuda.Malloc(out d_a, N * sizeof(float));
            cuda.Malloc(out d_b, N * sizeof(float));

            GCHandle handle_a = GCHandle.Alloc(a, GCHandleType.Pinned);
            GCHandle handle_b = GCHandle.Alloc(b, GCHandleType.Pinned);
            IntPtr h_a = handle_a.AddrOfPinnedObject();
            IntPtr h_b = handle_b.AddrOfPinnedObject();

            cuda.DeviceSynchronize();

            cuda.Memcpy(d_a, h_a, N * sizeof(float), cudaMemcpyKind.cudaMemcpyHostToDevice);
            cuda.Memcpy(d_b, h_b, N * sizeof(float), cudaMemcpyKind.cudaMemcpyHostToDevice);

            dynamic wrapped = HybRunner.Cuda().Wrap(new Program());

            wrapped.Add(d_a, d_b, N);

            cuda.DeviceSynchronize();

            cuda.Memcpy(h_a, d_a , N * sizeof(float), cudaMemcpyKind.cudaMemcpyDeviceToHost);

            for (int i = 0; i < N; ++i)
            {
                if (a[i] != (float)i + 1.0F)
                {
                    Console.Error.WriteLine("ERROR at {0} -- {1} != {2}", i, a[i], i + 1);
                    Environment.Exit(6); // abort
                }
            }

            handle_a.Free();
            handle_b.Free();
        }

19 View Source File : OvrWrap64.Common.cs
License : MIT License
Project Creator : ab4d

public override Result GetBoundaryGeometry(IntPtr sessionPtr, BoundaryType boundaryType, out Vector3f[] floorPoints)
        {
            int out_FloorPointsCount = 0;

            // In first call we get number of points back (called with floorPointPtr == Zero)
            var result = SafeNativeMethods.ovr_GetBoundaryGeometry(sessionPtr, boundaryType, IntPtr.Zero, ref out_FloorPointsCount);

            if (result != Result.Success || out_FloorPointsCount == 0)
            {
                floorPoints = null;
                return result;
            }

            floorPoints = new Vector3f[out_FloorPointsCount];

            GCHandle gcHandle = GCHandle.Alloc(floorPoints, GCHandleType.Pinned);

            try
            {
                result = SafeNativeMethods.ovr_GetBoundaryGeometry(sessionPtr, boundaryType, gcHandle.AddrOfPinnedObject(), ref out_FloorPointsCount);
            }
            finally
            {
                gcHandle.Free();
            }

            return result;
        }

19 View Source File : graybitmap.cs
License : MIT License
Project Creator : altimesh

public void Save(string filename)
        {
            using (BinaryWriter bw = new BinaryWriter(new FileStream(filename, FileMode.OpenOrCreate)))
            {
                // write headers
                FileHeader header = FileHeader.GrayBitmap(width, height);
                BitmapInfoHeader bih = BitmapInfoHeader.GrayBitmap(width, height);

                byte[] head = new byte[54];

                GCHandle gch = GCHandle.Alloc(header, GCHandleType.Pinned);
                Marshal.Copy(gch.AddrOfPinnedObject(), head, 0, 14);
                gch.Free();

                gch = GCHandle.Alloc(bih, GCHandleType.Pinned);
                Marshal.Copy(gch.AddrOfPinnedObject(), head, 14, 40);
                gch.Free();

                bw.Write(head, 0, 54);

                // write color table
                uint[] colors = new uint[256];
                uint color = 0;
                uint next = 0x010101;
                for (int k = 0; k < 256; ++k)
                {
                    bw.Write(color);
                    color += next;
                }

                // write data - note that bmp starts with bottom-left corner
                for (int y = 0; y < height; ++y)
                    bw.Write(data, (int)width * ((int)height - 1 - y), (int)width);
            }
        }

19 View Source File : Z85.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

public static byte[] Decode(byte[] encoded)
		{
			int dataLen = encoded.Length;
			if (dataLen % 5 > 0)
			{
				throw new InvalidOperationException("encoded.Length must be divisible by 5");
			}
			int destLen = (Int32)(encoded.Length * .8);

			var data = GCHandle.Alloc(encoded, GCHandleType.Pinned);

			using (var dest = DispoIntPtr.Alloc(destLen))
			{
				if (IntPtr.Zero == zmq.z85_decode(dest, data.AddrOfPinnedObject()))
				{
					data.Free();
					throw new InvalidOperationException();
				}
				data.Free();

				var decoded = new byte[destLen];

				Marshal.Copy(dest, decoded, 0, decoded.Length);

				return decoded;
			}
		}

19 View Source File : 04-stream-add.cs
License : MIT License
Project Creator : altimesh

unsafe static void Main(string[] args)
        {
            int nStreams = 8;
            cudaStream_t[] streams = new cudaStream_t[nStreams];
            
            //create streams

            int N = 1024 * 1024 * 32;
            float[] a = new float[N];
            float[] b = new float[N];

            for (int k = 0; k < N; ++k)
            {
                a[k] = (float)k;
                b[k] = 1.0F;
            }

            IntPtr d_a, d_b; // device pointers
            cuda.Malloc(out d_a, N * sizeof(float));
            cuda.Malloc(out d_b, N * sizeof(float));

            GCHandle handle_a = GCHandle.Alloc(a, GCHandleType.Pinned);
            GCHandle handle_b = GCHandle.Alloc(b, GCHandleType.Pinned);
            IntPtr h_a = handle_a.AddrOfPinnedObject();
            IntPtr h_b = handle_b.AddrOfPinnedObject();

            cuda.DeviceSynchronize();

            cuda.Memcpy(d_a, h_a, N * sizeof(float), cudaMemcpyKind.cudaMemcpyHostToDevice);
            cuda.Memcpy(d_b, h_b, N * sizeof(float), cudaMemcpyKind.cudaMemcpyHostToDevice);

            int slice = N / nStreams; // size of the array compute by each stream 

            dynamic wrapped = HybRunner.Cuda().Wrap(new Program());
            int start;
            int stop;
            
            // call kernel with each stream 

            // copy data device to host

            // synchronize and destroy streams

            for (int i = 0; i < N; ++i)
            {
                if (a[i] != (float)i + (1.0F * 100.0F))
                {
                    Console.Error.WriteLine("ERROR at {0} -- {1} != {2}", i, a[i], i + 1);
                    Environment.Exit(6); // abort
                }
            }

            handle_a.Free();
            handle_b.Free();
        }

19 View Source File : UnityRemoteVideo.cs
License : MIT License
Project Creator : 734843327

IntPtr PinByteArray(ref GCHandle handle, byte[] array)
		{
			handle.Free ();
			handle = GCHandle.Alloc (array, GCHandleType.Pinned);
			return handle.AddrOfPinnedObject ();
		}

19 View Source File : Utils.cs
License : MIT License
Project Creator : altskop

public static T FromBytes<T>(byte[] bytes)
        {
            GCHandle gcHandle = GCHandle.Alloc(bytes, GCHandleType.Pinned);
            var data = (T)Marshal.PtrToStructure(gcHandle.AddrOfPinnedObject(), typeof(T));
            gcHandle.Free();
            return data;
        }

19 View Source File : WaveOut.cs
License : GNU General Public License v3.0
Project Creator : ahmed605

public void Dispose()
        {
            if (m_Header.lpData != IntPtr.Zero)
            {
                WaveNative.waveOutUnprepareHeader(m_WaveOut, ref m_Header, Marshal.SizeOf(m_Header));
                m_HeaderHandle.Free();
                m_Header.lpData = IntPtr.Zero;
            }
            m_PlayEvent.Close();
            if (m_HeaderDataHandle.IsAllocated)
                m_HeaderDataHandle.Free();
            GC.SuppressFinalize(this);
        }

19 View Source File : VkString.cs
License : MIT License
Project Creator : amerkoleci

private void Dispose(bool disposing)
        {
            // Already disposed or not allocated?
            if (Size == 0)
                return;

            _handle.Free();
            Size = 0;
        }

19 View Source File : OvrWrapTest.cs
License : MIT License
Project Creator : ab4d

[TestMethod]
        public void Session_SubmitControllerVibration()
        {
            IntPtr sessionPtr = CreateSession();
            replacedert.AreNotEqual(IntPtr.Zero, sessionPtr);

            byte[] samples = { 0, 64, 128, 255 };
            var gcHandle = GCHandle.Alloc(samples, GCHandleType.Pinned);

            var hapticsBuffer = new HapticsBuffer()
            {
                Samples = gcHandle.AddrOfPinnedObject(),
                SamplesCount = samples.Length,
                SubmitMode = HapticsBufferSubmitMode.Enqueue
            };

            Result result = OVR.SubmitControllerVibration(sessionPtr, ControllerType.LTouch, hapticsBuffer);

            gcHandle.Free();

            replacedert.IsTrue(result >= Result.Success, "Failed to SubmitControllerVibration");
        }

19 View Source File : PropertyAccessor.cs
License : MIT License
Project Creator : amerkoleci

protected unsafe void SetObject(IntPtr guid, object value)
        {
            // NOT WORKING with APPDATA
            var prop = new PropertyPointer();
            InitHeader<PropertyPointer>(ref prop.Header);
            var dataValue = IntPtr.Zero;
            prop.Data = new UIntPtr(&dataValue);

            // Free previous application data if any
            Device.GetProperty(guid, new IntPtr(&prop));

            GCHandle handle;
            if ((long)prop.Data.ToUInt64() != -1)
            {
                IntPtr ptr = unchecked((IntPtr)(long)(ulong)prop.Data);

                handle = GCHandle.FromIntPtr(ptr);
                if (handle.IsAllocated)
                    handle.Free();
            }

            // Set new object value
            handle = GCHandle.Alloc(value, GCHandleType.Pinned);
            prop.Data =  unchecked((UIntPtr)(ulong)(long)handle.AddrOfPinnedObject()) ;
            Device.SetProperty(guid, new IntPtr(&prop));
        }

19 View Source File : MemoryManager.cs
License : MIT License
Project Creator : Akaion

internal void WriteVirtualMemory(IntPtr baseAddress, byte[] bytesToWrite)
        {
            // Adjust the protection of the virtual memory region to ensure it has write privileges
            
            var originalProtectionType = ProtectVirtualMemory(baseAddress, bytesToWrite.Length, MemoryProtection.ReadWrite);

            var bytesToWriteBufferHandle = GCHandle.Alloc(bytesToWrite, GCHandleType.Pinned);
            
            if (!WriteProcessMemory(_processHandle, baseAddress, bytesToWriteBufferHandle.AddrOfPinnedObject(), bytesToWrite.Length, IntPtr.Zero))
            {
                ExceptionHandler.ThrowWin32Exception("Failed to write into a region of virtual memory in the remote process");
            }
            
            // Restore the original protection of the virtual memory region
            
            ProtectVirtualMemory(baseAddress, bytesToWrite.Length, originalProtectionType);

            bytesToWriteBufferHandle.Free();
        }

19 View Source File : DataStream.cs
License : MIT License
Project Creator : amerkoleci

protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (_blob != null)
                {
                    _blob.Dispose();
                    _blob = null;
                }
            }

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

            if (_ownsBuffer && _buffer != (byte*)0)
            {
                MemoryHelpers.FreeMemory((IntPtr)_buffer);
                _buffer = (byte*)0;
            }
        }

19 View Source File : ManagedCompressedAV1Data.cs
License : MIT License
Project Creator : 0xC0000054

protected override void UnpinBuffer()
        {
            if (this.gcHandle.IsAllocated)
            {
                this.gcHandle.Free();
            }
        }

19 View Source File : ShaderIncludeHandler.cs
License : MIT License
Project Creator : amerkoleci

public void Dispose()
            {
                //_blob?.Dispose();
                _blob = null;

                if (_dataPointer.IsAllocated)
                    _dataPointer.Free();
                _dataPointer = default;
            }

19 View Source File : UntypedBuffer.cs
License : MIT License
Project Creator : Alan-FGR

public unsafe void PrintDebugData(int count, Type type)
    {
        List<String> strs = new List<String>();
        for (int i = 0; i < count; i++)
        {
            String str;
            try
            {
                var cast = Activator.CreateInstance(type);
                var handle = GCHandle.Alloc(cast, GCHandleType.Pinned);
                var addr = (void*)handle.AddrOfPinnedObject();
                Buffer.MemoryCopy(At(i), addr, ElementSizeInBytes, ElementSizeInBytes);
                handle.Free();
                str = cast.ToString();
                str = str.Substring(Math.Max(0, str.Length - 16), Math.Min(str.Length, 16)).PadLeft(16, '_');
            }
            catch (Exception e)
            {
                ulong ul = 0ul;
                Buffer.MemoryCopy(At(i), &ul, ElementSizeInBytes, ElementSizeInBytes);
                str = ul.ToString("X").PadLeft(16, '0');
            }
            strs.Add(str);
        }

        Console.ForegroundColor = ConsoleColor.Green;
        Console.WriteLine($"    {GetType()}<{type}>, elSize={ElementSizeInBytes}, bfSize={bufferSizeInBytes_}, ptr={buffer_}, unaligned={unalignedPtr_}");
        Console.ForegroundColor = ConsoleColor.Cyan;
        Console.WriteLine($"      objs: {String.Join(", ", strs)}");
    }

19 View Source File : OVRLipSync.cs
License : MIT License
Project Creator : absurd-joy

public static Result ProcessFrame(
        uint context, float[] audioBuffer, Frame frame, bool stereo = true)
    {
        if (IsInitialized() != Result.Success)
            return Result.Unknown;

        var dataType = stereo ? AudioDataType.F32_Stereo : AudioDataType.F32_Mono;
        var numSamples = (uint)(stereo ? audioBuffer.Length / 2 : audioBuffer.Length);
        var handle = GCHandle.Alloc(audioBuffer, GCHandleType.Pinned);
        var rc = ovrLipSyncDll_ProcessFrameEx(context,
                                              handle.AddrOfPinnedObject(), numSamples, dataType,
                                              ref frame.frameNumber, ref frame.frameDelay,
                                              frame.Visemes, frame.Visemes.Length,
                                              ref frame.laughterScore,
                                              null, 0
                                              );
        handle.Free();
        return (Result)rc;

    }

19 View Source File : ManagedCompressedAV1Data.cs
License : MIT License
Project Creator : 0xC0000054

protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                DisposableUtil.Free(ref this.buffer);
            }

            if (this.gcHandle.IsAllocated)
            {
                this.gcHandle.Free();
            }

            base.Dispose(disposing);
        }

19 View Source File : AreaForm.cs
License : MIT License
Project Creator : 1CM69

public static Cursor LoadEmbeddedCursor(byte[] cursorResource, int imageIndex = 0)
            {
                var resourceHandle = GCHandle.Alloc(cursorResource, GCHandleType.Pinned);
                var iconImage = IntPtr.Zero;
                var cursorHandle = IntPtr.Zero;

                try
                {
                    var header = (IconHeader)Marshal.PtrToStructure(resourceHandle.AddrOfPinnedObject(), typeof(IconHeader));

                    if (imageIndex >= header.count)
                        throw new ArgumentOutOfRangeException("imageIndex");

                    var iconInfoPtr = resourceHandle.AddrOfPinnedObject() + Marshal.SizeOf(typeof(IconHeader)) + imageIndex * Marshal.SizeOf(typeof(IconInfo));
                    var info = (IconInfo)Marshal.PtrToStructure(iconInfoPtr, typeof(IconInfo));

                    iconImage = Marshal.AllocHGlobal(info.size + 4);
                    Marshal.WriteInt16(iconImage + 0, info.hotspot_x);
                    Marshal.WriteInt16(iconImage + 2, info.hotspot_y);
                    Marshal.Copy(cursorResource, info.offset, iconImage + 4, info.size);

                    cursorHandle = NativeMethods.CreateIconFromResource(iconImage, info.size + 4, false, 0x30000);
                    return new Cursor(cursorHandle);
                }
                finally
                {
                    if (cursorHandle != IntPtr.Zero)
                        NativeMethods.DestroyIcon(cursorHandle);

                    if (iconImage != IntPtr.Zero)
                        Marshal.FreeHGlobal(iconImage);

                    if (resourceHandle.IsAllocated)
                        resourceHandle.Free();
                }
            }

19 View Source File : OvrWrap64.Common.cs
License : MIT License
Project Creator : ab4d

public override void GetEyePoses(IntPtr sessionPtr, long frameIndex, bool latencyMarker, Vector3f[] hmdToEyeOffset, ref Posef[] eyePoses, out double sensorSampleTime)
        {
            if (eyePoses == null)
                throw new ArgumentNullException("eyePoses");

            if (eyePoses.Length != 2)
                throw new ArgumentException("eyePoses array should have 2 Posef items", "eyePoses");


            GCHandle posesHandle = GCHandle.Alloc(eyePoses, GCHandleType.Pinned);
            try
            {
                sensorSampleTime = 0;
                SafeNativeMethods.ovr_GetEyePoses(sessionPtr, frameIndex, latencyMarker ? (byte)1 : (byte)0, hmdToEyeOffset, posesHandle.AddrOfPinnedObject(), ref sensorSampleTime);
            }
            finally
            {
                posesHandle.Free();
            }
        }

19 View Source File : WindowLayoutChanged.cs
License : GNU General Public License v3.0
Project Creator : Adam-Wilkinson

public void RemoveTriggers()
        {
            if (_gcSafetyHandle.IsAllocated)
            {
                _gcSafetyHandle.Free();
            }
            WindowHooks.WinEventUnhook(_hook);
            WindowHooks.WinEventUnhook(_hook2);
            WindowHooks.WindowArrangementManuallyChanged -= ArrangementChanged;

        }

19 View Source File : Program.cs
License : MIT License
Project Creator : altimesh

static void Main(string[] args)
        {
            // init CUDA
            IntPtr d;
            cuda.Malloc(out d, sizeof(int));
            cuda.Free(d);

            HybRunner runner = HybRunner.Cuda();
            cudaDeviceProp prop;
            cuda.GetDeviceProperties(out prop, 0);
            dynamic wrapped = runner.Wrap(new Program());
            runner.savereplacedembly();
            cudaStream_t stream;
            cuda.StreamCreate(out stream);

            NppStreamContext context = new NppStreamContext
            {
                hStream = stream,
                nCudaDevAttrComputeCapabilityMajor = prop.major,
                nCudaDevAttrComputeCapabilityMinor = prop.minor,
                nCudaDeviceId = 0,
                nMaxThreadsPerBlock = prop.maxThreadsPerBlock,
                nMaxThreadsPerMultiProcessor = prop.maxThreadsPerMultiProcessor,
                nMultiProcessorCount = prop.multiProcessorCount,
                nSharedMemPerBlock = 0
            };

            Random rand = new Random();

            using (NPPImage input = NPPImage.Load(inputFileName, stream))
            {
                uchar4[] output = new uchar4[input.width * input.height];
                IntPtr d_output;
                cuda.Malloc(out d_output, input.width * input.height * 4 * sizeof(byte));

                // working area 
                IntPtr oDeviceDst32u;
                size_t oDeviceDst32uPitch;
                cuda.ERROR_CHECK(cuda.MallocPitch(out oDeviceDst32u, out oDeviceDst32uPitch, input.width * sizeof(int), input.height));
                IntPtr segments;
                size_t segmentsPitch;
                cuda.ERROR_CHECK(cuda.MallocPitch(out segments, out segmentsPitch, input.width * sizeof(ushort), input.height));

                NppiSize oSizeROI = new NppiSize { width = input.width, height = input.height };
                int nBufferSize = 0;
                IntPtr pScratchBufferNPP1, pScratchBufferNPP2;

                // compute maximum label
                NPPI.ERROR_CHECK(NPPI.LabelMarkersGetBufferSize_16u_C1R(oSizeROI, out nBufferSize));
                cuda.ERROR_CHECK(cuda.Malloc(out pScratchBufferNPP1, nBufferSize));
                int maxLabel;
                NPPI.ERROR_CHECK(NPPI.LabelMarkers_16u_C1IR_Ctx(input.deviceData, input.pitch, oSizeROI, 165, NppiNorm.nppiNormInf, out maxLabel, pScratchBufferNPP1, context));


                // compress labels
                NPPI.ERROR_CHECK(NPPI.CompressMarkerLabelsGetBufferSize_16u_C1R(maxLabel, out nBufferSize));
                cuda.ERROR_CHECK(cuda.Malloc(out pScratchBufferNPP2, nBufferSize));
                NPPI.ERROR_CHECK(NPPI.CompressMarkerLabels_16u_C1IR_Ctx(input.deviceData, input.pitch, oSizeROI, maxLabel, out maxLabel, pScratchBufferNPP2, context));

                uchar4[] colormap = new uchar4[maxLabel + 1];
                for (int i = 0; i <= maxLabel; ++i)
                {
                    colormap[i] = new uchar4 { x = (byte)(rand.Next() % 256), y = (byte)(rand.Next() % 256), z = (byte)(rand.Next() % 256), w = 0 };
                }

                IntPtr d_colormap;
                cuda.Malloc(out d_colormap, (maxLabel + 1) * 4 * sizeof(byte));
                var handle = GCHandle.Alloc(colormap, GCHandleType.Pinned);
                cuda.Memcpy(d_colormap, handle.AddrOfPinnedObject(), (maxLabel + 1) * 4 * sizeof(byte), cudaMemcpyKind.cudaMemcpyHostToDevice);
                handle.Free();

                NPP_ImageSegmentationx46Programx46ColorizeLabels_ExternCWrapperStream_CUDA(
                    8 * prop.multiProcessorCount, 1, 256, 1, 1, 0, stream, // cuda configuration
                    input.deviceData, d_output, d_colormap, maxLabel + 1, input.pitch * input.height / sizeof(ushort), input.width, input.pitch / sizeof(ushort));

                handle = GCHandle.Alloc(output, GCHandleType.Pinned);
                cuda.Memcpy(handle.AddrOfPinnedObject(), d_output, input.width * input.height * sizeof(byte) * 4, cudaMemcpyKind.cudaMemcpyDeviceToHost);
                handle.Free();
                NPPImage.Save(segmentsFileName, output, input.width, input.height);
                Process.Start(segmentsFileName);

                cuda.ERROR_CHECK(cuda.Free(oDeviceDst32u));
                cuda.ERROR_CHECK(cuda.Free(segments));
                cuda.ERROR_CHECK(cuda.Free(pScratchBufferNPP1));
                cuda.ERROR_CHECK(cuda.Free(pScratchBufferNPP2));
            }
        }

See More Examples