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 Source : AudioDevices.cs
with GNU General Public License v3.0
from BRH-Media

private void InputMeter_GetValues()
        {
            if (pm_HasInputMeter)
            {
                GCHandle values = GCHandle.Alloc(pm_InputMeterValues, GCHandleType.Pinned);
                //pm_PeakMeterInfo.GetMeteringChannelCount(out pm_PeakMeterChannelCount);
                pm_InputMeterInfo.GetChannelsPeakValues(pm_InputMeterChannelCount, values.AddrOfPinnedObject());
                pm_InputMeterInfo.GetPeakValue(out pm_InputMeterMasterValue);
                values.Free();
            }
            else
            {
                for (int i = 0; i < MAX_AUDIO_CHANNELS; i++) { pm_InputMeterValues[i] = STOP_VALUE; }
            }
        }

19 Source : AudioDevices.cs
with GNU General Public License v3.0
from BRH-Media

private void PeakMeter_GetValues()
        {
            if (pm_HasPeakMeter)
            {
                GCHandle values = GCHandle.Alloc(pm_PeakMeterValues, GCHandleType.Pinned);
                if (pm_PeakMeterInfo.GetChannelsPeakValues(pm_PeakMeterChannelCount, values.AddrOfPinnedObject()) == NO_ERROR)
                {
                    pm_PeakMeterInfo.GetPeakValue(out pm_PeakMeterMasterValue);
                }
                else if (pm_PeakMeterValues[0] != STOP_VALUE)
                {
                    for (int i = 0; i < MAX_AUDIO_CHANNELS; i++) { pm_PeakMeterValues[i] = STOP_VALUE; }
                    pm_PeakMeterMasterValue = 0;
                }
                values.Free();
            }
            else
            {
                for (int i = 0; i < MAX_AUDIO_CHANNELS; i++) { pm_PeakMeterValues[i] = STOP_VALUE; }
            }
        }

19 Source : UnsafeUtilities.cs
with MIT License
from BrunoS3D

public static unsafe int StringToBytes(byte[] buffer, string value, bool needs16BitSupport)
        {
            int byteCount = needs16BitSupport ? value.Length * 2 : value.Length;

            if (buffer.Length < byteCount)
            {
                throw new ArgumentException("Buffer is not large enough to contain the given string; a size of at least " + byteCount + " is required.");
            }

            GCHandle toHandle = default(GCHandle);

            try
            {
                toHandle = GCHandle.Alloc(buffer, GCHandleType.Pinned);

                if (needs16BitSupport)
                {
                    if (BitConverter.IsLittleEndian)
                    {
                        fixed (char* charPtr1 = value)
                        {
                            ushort* fromPtr1 = (ushort*)charPtr1;
                            ushort* toPtr1 = (ushort*)toHandle.AddrOfPinnedObject().ToPointer();

                            for (int i = 0; i < byteCount; i += sizeof(ushort))
                            {
                                *toPtr1++ = *fromPtr1++;
                            }
                        }
                    }
                    else
                    {
                        fixed (char* charPtr2 = value)
                        {
                            byte* fromPtr2 = (byte*)charPtr2;
                            byte* toPtr2 = (byte*)toHandle.AddrOfPinnedObject().ToPointer();

                            for (int i = 0; i < byteCount; i += sizeof(ushort))
                            {
                                *toPtr2 = *(fromPtr2 + 1);
                                *(toPtr2 + 1) = *fromPtr2;

                                fromPtr2 += 2;
                                toPtr2 += 2;
                            }
                        }
                    }
                }
                else
                {
                    if (BitConverter.IsLittleEndian)
                    {
                        fixed (char* charPtr3 = value)
                        {
                            byte* fromPtr3 = (byte*)charPtr3;
                            byte* toPtr3 = (byte*)toHandle.AddrOfPinnedObject().ToPointer();

                            for (int i = 0; i < byteCount; i += sizeof(byte))
                            {
                                fromPtr3++; // Skip every other string byte
                                *toPtr3++ = *fromPtr3++;
                            }
                        }
                    }
                    else
                    {
                        fixed (char* charPtr4 = value)
                        {
                            byte* fromPtr4 = (byte*)charPtr4;
                            byte* toPtr4 = (byte*)toHandle.AddrOfPinnedObject().ToPointer();

                            for (int i = 0; i < byteCount; i += sizeof(byte))
                            {
                                *toPtr4++ = *fromPtr4++;
                                fromPtr4++; // Skip every other string byte
                            }
                        }
                    }
                }
            }
            finally
            {
                if (toHandle.IsAllocated)
                {
                    toHandle.Free();
                }
            }

            return byteCount;
        }

19 Source : UnsafeUtilities.cs
with MIT License
from BrunoS3D

public static unsafe string StringFromBytes(byte[] buffer, int charLength, bool needs16BitSupport)
        {
            int byteCount = needs16BitSupport ? charLength * 2 : charLength;

            if (buffer.Length < byteCount)
            {
                throw new ArgumentException("Buffer is not large enough to contain the given string; a size of at least " + byteCount + " is required.");
            }

            GCHandle toHandle = default(GCHandle);
            string result = new string(default(char), charLength); // Creaty empty string of required length

            try
            {
                toHandle = GCHandle.Alloc(buffer, GCHandleType.Pinned);

                if (needs16BitSupport)
                {
                    if (BitConverter.IsLittleEndian)
                    {
                        fixed (char* charPtr1 = result)
                        {
                            ushort* fromPtr1 = (ushort*)toHandle.AddrOfPinnedObject().ToPointer();
                            ushort* toPtr1 = (ushort*)charPtr1;

                            for (int i = 0; i < byteCount; i += sizeof(ushort))
                            {
                                *toPtr1++ = *fromPtr1++;
                            }
                        }
                    }
                    else
                    {
                        fixed (char* charPtr2 = result)
                        {
                            byte* fromPtr2 = (byte*)toHandle.AddrOfPinnedObject().ToPointer();
                            byte* toPtr2 = (byte*)charPtr2;

                            for (int i = 0; i < byteCount; i += sizeof(ushort))
                            {
                                *toPtr2 = *(fromPtr2 + 1);
                                *(toPtr2 + 1) = *fromPtr2;

                                fromPtr2 += 2;
                                toPtr2 += 2;
                            }
                        }
                    }
                }
                else
                {
                    if (BitConverter.IsLittleEndian)
                    {
                        fixed (char* charPtr3 = result)
                        {
                            byte* fromPtr3 = (byte*)toHandle.AddrOfPinnedObject().ToPointer();
                            byte* toPtr3 = (byte*)charPtr3;

                            for (int i = 0; i < byteCount; i += sizeof(byte))
                            {
                                *toPtr3++ = *fromPtr3++;
                                toPtr3++; // Skip every other string byte
                            }
                        }
                    }
                    else
                    {
                        fixed (char* charPtr4 = result)
                        {
                            byte* fromPtr4 = (byte*)toHandle.AddrOfPinnedObject().ToPointer();
                            byte* toPtr4 = (byte*)charPtr4;

                            for (int i = 0; i < byteCount; i += sizeof(byte))
                            {
                                toPtr4++; // Skip every other string byte
                                *toPtr4++ = *fromPtr4++;
                            }
                        }
                    }
                }
            }
            finally
            {
                if (toHandle.IsAllocated)
                {
                    toHandle.Free();
                }
            }

            // Retrieve proper string reference from the intern pool.
            // This code removed for now, as the slight decrease in memory use is not considered worth the performance cost of the intern lookup and the potential extra garbage to be collected.
            // Might eventually become a global config option, if this is considered necessary.
            //result = string.Intern(result);

            return result;
        }

19 Source : UnsafeUtilities.cs
with MIT License
from BrunoS3D

public static unsafe void MemoryCopy(object from, object to, int byteCount, int fromByteOffset, int toByteOffset)
        {
            GCHandle fromHandle = default(GCHandle);
            GCHandle toHandle = default(GCHandle);

            if (fromByteOffset % sizeof(ulong) != 0 || toByteOffset % sizeof(ulong) != 0)
            {
                throw new ArgumentException("Byte offset must be divisible by " + sizeof(ulong) + " (IE, sizeof(ulong))");
            }

            try
            {
                int restBytes = byteCount % sizeof(ulong);
                int ulongCount = (byteCount - restBytes) / sizeof(ulong);
                int fromOffsetCount = fromByteOffset / sizeof(ulong);
                int toOffsetCount = toByteOffset / sizeof(ulong);

                fromHandle = GCHandle.Alloc(from, GCHandleType.Pinned);
                toHandle = GCHandle.Alloc(to, GCHandleType.Pinned);

                ulong* fromUlongPtr = (ulong*)fromHandle.AddrOfPinnedObject().ToPointer();
                ulong* toUlongPtr = (ulong*)toHandle.AddrOfPinnedObject().ToPointer();

                if (fromOffsetCount > 0)
                {
                    fromUlongPtr += fromOffsetCount;
                }

                if (toOffsetCount > 0)
                {
                    toUlongPtr += toOffsetCount;
                }

                for (int i = 0; i < ulongCount; i++)
                {
                    *toUlongPtr++ = *fromUlongPtr++;
                }

                if (restBytes > 0)
                {
                    byte* fromBytePtr = (byte*)fromUlongPtr;
                    byte* toBytePtr = (byte*)toUlongPtr;

                    for (int i = 0; i < restBytes; i++)
                    {
                        *toBytePtr++ = *fromBytePtr++;
                    }
                }
            }
            finally
            {
                if (fromHandle.IsAllocated)
                {
                    fromHandle.Free();
                }

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

19 Source : DataMemory.cs
with MIT License
from bryanperris

protected virtual void Dispose(bool disposing)
        {
            if (!disposedValue)
            {
                if (disposing)
                {
                    m_DataStream.Dispose();
                }

                m_BufferPtr = IntPtr.Zero;
                m_BufferHandle.Free();

                disposedValue = true;
            }
        }

19 Source : NativeMetadataCredentialsPlugin.cs
with MIT License
from bwplotka

private void NativeMetadataInterceptorHandler(IntPtr statePtr, IntPtr serviceUrlPtr, IntPtr methodNamePtr, IntPtr callbackPtr, IntPtr userDataPtr, bool isDestroy)
        {
            if (isDestroy)
            {
                gcHandle.Free();
                return;
            }

            try
            {
                var context = new AuthInterceptorContext(Marshal.PtrToStringAnsi(serviceUrlPtr),
                                                         Marshal.PtrToStringAnsi(methodNamePtr));
                // Don't await, we are in a native callback and need to return.
                GetMetadataAsync(context, callbackPtr, userDataPtr).Subscribe();
            }
            catch (Exception e)
            {
                Native.grpcsharp_metadata_credentials_notify_from_plugin(callbackPtr, userDataPtr, MetadataArraySafeHandle.Create(Metadata.Empty), StatusCode.Unknown, GetMetadataExceptionMsg);
                Logger.Error(e, GetMetadataExceptionMsg);
            }
        }

19 Source : WasiConfiguration.cs
with Apache License 2.0
from bytecodealliance

private unsafe void SetConfigArgs(Handle config)
        {
            // Don't call wasi_config_inherit_argv as the command line to the .NET program may not be
            // the same as the process' command line (e.g. `dotnet foo.dll foo bar baz` => "foo.dll foo bar baz").
            if (_args.Count == 0)
            {
                return;
            }

            var (args, handles) = ToUTF8PtrArray(_args);

            try
            {
                fixed (byte** arrayOfStringsPtrNamedArgs = args)
                {
                    Native.wasi_config_set_argv(config, _args.Count, arrayOfStringsPtrNamedArgs);
                }
            }
            finally
            {
                foreach (var handle in handles)
                {
                    handle.Free();
                }
            }
        }

19 Source : WasiConfiguration.cs
with Apache License 2.0
from bytecodealliance

private unsafe void SetEnvironmentVariables(Handle config)
        {
            if (_inheritEnv)
            {
                Native.wasi_config_inherit_env(config);
                return;
            }

            if (_vars.Count == 0)
            {
                return;
            }

            var (names, nameHandles) = ToUTF8PtrArray(_vars.Select(var => var.Name).ToArray());
            var (values, valueHandles) = ToUTF8PtrArray(_vars.Select(var => var.Value).ToArray());

            try
            {
                Native.wasi_config_set_env(config, _vars.Count, names, values);
            }
            finally
            {
                foreach (var handle in nameHandles)
                {
                    handle.Free();
                }

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

19 Source : SymWriter.cs
with MIT License
from CatLib

public void DefineCustomMetadata (string name, byte [] metadata)
		{
			var handle = GCHandle.Alloc (metadata, GCHandleType.Pinned);
			m_writer.SetSymAttribute (0, name, (uint) metadata.Length, handle.AddrOfPinnedObject ());
			handle.Free ();
		}

19 Source : CLRRedirections.cs
with MIT License
from CatLib

public unsafe static StackObject* InitializeArray(ILIntepreter intp, StackObject* esp, IList<object> mStack, CLRMethod method, bool isNewObj)
        {
            var ret = esp - 1 - 1;
            AppDomain domain = intp.AppDomain;
            var param = esp - 1;
            byte[] data = StackObject.ToObject(param, domain, mStack) as byte[];
            intp.Free(param);
            param = esp - 1 - 1;
            object array = StackObject.ToObject(param, domain, mStack);
            intp.Free(param);

            if (data == null)
                return ret;
            fixed (byte* p = data)
            {
                /*Array oArr = (Array)array;
                if (oArr.Rank == 1)
                {
                    if (array is int[])
                    {
                        int[] arr = array as int[];
                        int* ptr = (int*)p;
                        for (int i = 0; i < arr.Length; i++)
                        {
                            arr[i] = ptr[i];
                        }
                    }
                    else if (array is byte[])
                    {
                        byte[] arr = array as byte[];
                        for (int i = 0; i < arr.Length; i++)
                        {
                            arr[i] = p[i];
                        }
                    }
                    else if (array is sbyte[])
                    {
                        sbyte[] arr = array as sbyte[];
                        sbyte* ptr = (sbyte*)p;
                        for (int i = 0; i < arr.Length; i++)
                        {
                            arr[i] = ptr[i];
                        }
                    }
                    else if (array is short[])
                    {
                        short[] arr = array as short[];
                        short* ptr = (short*)p;
                        for (int i = 0; i < arr.Length; i++)
                        {
                            arr[i] = ptr[i];
                        }
                    }
                    else if (array is ushort[])
                    {
                        ushort[] arr = array as ushort[];
                        ushort* ptr = (ushort*)p;
                        for (int i = 0; i < arr.Length; i++)
                        {
                            arr[i] = ptr[i];
                        }
                    }
                    else if (array is char[])
                    {
                        char[] arr = array as char[];
                        char* ptr = (char*)p;
                        for (int i = 0; i < arr.Length; i++)
                        {
                            arr[i] = ptr[i];
                        }
                    }
                    else if (array is uint[])
                    {
                        uint[] arr = array as uint[];
                        uint* ptr = (uint*)p;
                        for (int i = 0; i < arr.Length; i++)
                        {
                            arr[i] = ptr[i];
                        }
                    }
                    else if (array is Int64[])
                    {
                        long[] arr = array as long[];
                        long* ptr = (long*)p;
                        for (int i = 0; i < arr.Length; i++)
                        {
                            arr[i] = ptr[i];
                        }
                    }
                    else if (array is UInt64[])
                    {
                        ulong[] arr = array as ulong[];
                        ulong* ptr = (ulong*)p;
                        for (int i = 0; i < arr.Length; i++)
                        {
                            arr[i] = ptr[i];
                        }
                    }
                    else if (array is float[])
                    {
                        float[] arr = array as float[];
                        float* ptr = (float*)p;
                        for (int i = 0; i < arr.Length; i++)
                        {
                            arr[i] = ptr[i];
                        }
                    }
                    else if (array is double[])
                    {
                        double[] arr = array as double[];
                        double* ptr = (double*)p;
                        for (int i = 0; i < arr.Length; i++)
                        {
                            arr[i] = ptr[i];
                        }
                    }
                    else if (array is bool[])
                    {
                        bool[] arr = array as bool[];
                        bool* ptr = (bool*)p;
                        for (int i = 0; i < arr.Length; i++)
                        {
                            arr[i] = ptr[i];
                        }
                    }
                    else
                    {
                        throw new NotImplementedException("array=" + array.GetType());
                    }
                }
                else
                {
                    int* dst = (int*)System.Runtime.InteropServices.Marshal.UnsafeAddrOfPinnedArrayElement(oArr, 0).ToPointer();

                        int* src = (int*)p;
                        int len = data.Length / sizeof(int);
                        for (int i = 0; i < len; i++)
                            dst[i] = src[i];
                    
                }*/
                Array arr = (Array)array;
                var handle = System.Runtime.InteropServices.GCHandle.Alloc(arr, System.Runtime.InteropServices.GCHandleType.Pinned);
                var dst = System.Runtime.InteropServices.Marshal.UnsafeAddrOfPinnedArrayElement(arr, 0);
                System.Runtime.InteropServices.Marshal.Copy(data, 0, dst, data.Length);
                handle.Free();
            }

            return ret;
        }

19 Source : AlignedArrayPool.cs
with MIT License
from CBGonzalez

public unsafe void Return(AlignedMemoryHandle<T> bufferHandle, bool clearArray = false)
        {
            (MemoryHandle memHandle, GCHandle gcHandle, byte[] buff) item;
            lock (lockObject)
            {
                for (int i = 0; i < allMemoryHandles.Count; i++)
                {
                    item = allMemoryHandles[i];
                    if (item.memHandle.Pointer == bufferHandle.MemoryHandle.Pointer)
                    {
                        if (item.gcHandle.IsAllocated)
                        {
                            item.gcHandle.Free();
                        }
                        pool.Return(item.buff, clearArray);
                        allMemoryHandles.RemoveAt(i);
                        break;
                    }
                }
            }
        }

19 Source : AlignedArrayPool.cs
with MIT License
from CBGonzalez

protected virtual void Dispose(bool disposing)
        {
            if (!disposedValue)
            {
                if (disposing)
                {
                    // TODO: dispose managed state (managed objects).
                }

                // TODO: free unmanaged resources (unmanaged objects) and override a finalizer below.
                // TODO: set large fields to null.
                if (allMemoryHandles.Count > 0)
                {
                    (MemoryHandle memHandle, GCHandle gcHandle, byte[] buff) item;
                    for (int i = 0; i < allMemoryHandles.Count; i++)
                    {
                        item = allMemoryHandles[i];                        
                        if (item.gcHandle.IsAllocated)
                        {
                            item.gcHandle.Free();
                        }
                        pool.Return(item.buff);
                        
                    }
                    allMemoryHandles.Clear();
                    allBuffers.Clear();
                }

                disposedValue = true;
            }
        }

19 Source : PoolArena.cs
with Apache License 2.0
from cdy816

void Release()
            {
                if (this.handle.IsAllocated)
                {
                    try
                    {
                        this.handle.Free();
                    }
                    catch (InvalidOperationException)
                    {
                        // Free is not thread safe
                    }
                }
                this.Bytes = null;
            }

19 Source : Loop.cs
with Apache License 2.0
from cdy816

static void Close(IntPtr handle)
        {
            if (handle == IntPtr.Zero)
            {
                return;
            }

            // Get gc handle before close loop
            IntPtr pHandle = ((uv_loop_t*)handle)->data;

            // Fully close the loop, similar to 
            //https://github.com/libuv/libuv/blob/v1.x/test/task.h#L190

            int count = 0;
            while (true)
            {
                ////Logger.Debug($"Loop {handle} walking handles, count = {count}.");
                NativeMethods.uv_walk(handle, WalkCallback, handle);

                ////Logger.Debug($"Loop {handle} running default to call close callbacks, count = {count}.");
                NativeMethods.uv_run(handle, uv_run_mode.UV_RUN_DEFAULT);

                int result = NativeMethods.uv_loop_close(handle);
                ////Logger.Debug($"Loop {handle} close result = {result}, count = {count}.");
                if (result == 0)
                {
                    break;
                }

                count++;
                if (count >= 20)
                {
                    ////Logger.Warn($"Loop {handle} close all handles limit 20 times exceeded.");
                    break;
                }
            }
            ////Logger.Info($"Loop {handle} closed, count = {count}.");

            // Free GCHandle
            if (pHandle != IntPtr.Zero)
            {
                GCHandle nativeHandle = GCHandle.FromIntPtr(pHandle);
                if (nativeHandle.IsAllocated)
                {
                    nativeHandle.Free();
                    ((uv_loop_t*)handle)->data = IntPtr.Zero;
                    //Logger.Info($"Loop {handle} GCHandle released.");
                }
            }

            // Release memory
            NativeMethods.FreeMemory(handle);
            //Logger.Info($"Loop {handle} memory released.");
        }

19 Source : NativeHandle.cs
with Apache License 2.0
from cdy816

static void OnCloseHandle(IntPtr handle)
        {
            if (handle == IntPtr.Zero)
            {
                return;
            }

            NativeHandle nativeHandle = null;

            // Get gc handle first
            IntPtr pHandle = ((uv_handle_t*)handle)->data;
            if (pHandle != IntPtr.Zero)
            {
                GCHandle gcHandle = GCHandle.FromIntPtr(pHandle);
                if (gcHandle.IsAllocated)
                {
                    nativeHandle = gcHandle.Target as NativeHandle;
                    gcHandle.Free();

                    ((uv_handle_t*)handle)->data = IntPtr.Zero;
                }
            }

            // Release memory
            NativeMethods.FreeMemory(handle);
            nativeHandle?.OnClosed();
        }

19 Source : NativeRequest.cs
with Apache License 2.0
from cdy816

protected void CloseHandle()
        {
            IntPtr handle = this.Handle;
            if (handle == IntPtr.Zero)
            {
                return;
            }

            IntPtr pHandle = ((uv_req_t*)handle)->data;

            // Free GCHandle
            if (pHandle != IntPtr.Zero)
            {
                GCHandle nativeHandle = GCHandle.FromIntPtr(pHandle);
                if (nativeHandle.IsAllocated)
                {
                    nativeHandle.Free();
                    ((uv_req_t*)handle)->data = IntPtr.Zero;
                }
            }

            // Release memory
            NativeMethods.FreeMemory(handle);
            this.Handle = IntPtr.Zero;
        }

19 Source : Pipe.cs
with Apache License 2.0
from cdy816

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

19 Source : Pipe.cs
with Apache License 2.0
from cdy816

protected override void Dispose(bool disposing)
            {
                if (this.gcHandle.IsAllocated)
                {
                    this.gcHandle.Free();
                }
                base.Dispose(disposing);
            }

19 Source : ReadOperation.cs
with Apache License 2.0
from cdy816

void Release()
        {
            if (this.pin.IsAllocated)
            {
                this.pin.Free();
            }
        }

19 Source : WriteRequest.cs
with Apache License 2.0
from cdy816

void Release()
        {
            if (this.handles.Count > 0)
            {
                for (int i = 0; i < this.handles.Count; i++)
                {
                    if (this.handles[i].IsAllocated)
                    {
                        this.handles[i].Free();
                    }
                }
                this.handles.Clear();
            }

            this.nativeUnsafe = null;
            this.count = 0;
            this.size = 0;
            this.recyclerHandle.Release(this);
        }

19 Source : WriteRequest.cs
with Apache License 2.0
from cdy816

void Free()
        {
            this.Release();
            if (this.pin.IsAllocated)
            {
                this.pin.Free();
            }
            this.bufs = IntPtr.Zero;
        }

19 Source : XrayObject.cs
with MIT License
from CefNet

internal void ReleaseHandle()
		{
			if (0 == Interlocked.Decrement(ref _refcount))
			{
				_handle.Free();
				Dispose();
			}
		}

19 Source : XrayProxy.cs
with MIT License
from CefNet

private void Dispose(bool disposing)
		{
			if (_providerHandle.IsAllocated)
			{
				if (!Environment.HreplacedhutdownStarted)
				{
					Provider?.ReleaseObject(_instance);
				}
				_providerHandle.Free();
			}
		}

19 Source : XrayHandle.cs
with MIT License
from CefNet

public unsafe CefBinaryValue ToCfxBinaryValue()
		{
			CefBinaryValue value;
			GCHandle handle = GCHandle.Alloc(this, GCHandleType.Pinned);
			value = new CefBinaryValue(handle.AddrOfPinnedObject(), sizeof(XrayHandle));
			handle.Free();
			return value;
		}

19 Source : ArrayBuffer.cs
with MIT License
from CefNet

protected override void Dispose(bool disposing)
		{
			_handle?.Free();
			_handle = null;
		}

19 Source : Crypto_Operation.cs
with GNU Affero General Public License v3.0
from ceramicskate0

internal static void Clear_Preplacedword()
        {
            GCHandle gch = GCHandle.Alloc(GET_Preplacedword(), GCHandleType.Pinned);
            ZeroMemory(gch.AddrOfPinnedObject(), GET_Preplacedword().Length * 2);
            gch.Free();
        }

19 Source : PELoader.cs
with The Unlicense
from ceramicskate0

public static T FromBinaryReader<T>(BinaryReader reader)
        {
            // Read in a byte array
            byte[] bytes = reader.ReadBytes(Marshal.SizeOf(typeof(T)));

            // Pin the managed memory while, copy it out the data, then unpin it
            GCHandle handle = GCHandle.Alloc(bytes, GCHandleType.Pinned);
            T theStructure = (T)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(T));
            handle.Free();

            return theStructure;
        }

19 Source : PeUtility.cs
with GNU General Public License v3.0
from chaincase-app

public static T FromBinaryReader<T>(BinaryReader reader)
		{
			// Read in a byte array
			var bytes = reader.ReadBytes(Marshal.SizeOf<T>());

			// Pin the managed memory while, copy it out the data, then unpin it
			var handle = GCHandle.Alloc(bytes, GCHandleType.Pinned);
			var theStructure = Marshal.PtrToStructure<T>(handle.AddrOfPinnedObject());
			handle.Free();

			return theStructure;
		}

19 Source : PDFConvert.cs
with MIT License
from chen0040

private void ClearParameters(ref GCHandle[] aGCHandle, ref GCHandle gchandleArgs)
        {
            for (int intCounter = 0; intCounter < aGCHandle.Length; intCounter++)
                aGCHandle[intCounter].Free();
            gchandleArgs.Free();
        }

19 Source : PDFConvert.cs
with MIT License
from chen0040

public int gsdll_stdin(IntPtr intGSInstanceHandle, IntPtr strz, int intBytes)
        {
            // This is dumb code that reads one byte at a time
           // Ghostscript doesn't mind this, it is just very slow
            if (intBytes == 0) 
                return 0;
            else
            {
                int ich = Console.Read();
                if (ich == -1)
                    return 0; // EOF
                else
                {
                    byte bch = (byte)ich;
                    GCHandle gcByte = GCHandle.Alloc(bch, GCHandleType.Pinned);
                    IntPtr ptrByte = gcByte.AddrOfPinnedObject();
                    CopyMemory(strz, ptrByte, 1);
                    ptrByte = IntPtr.Zero;
                    gcByte.Free();
                    return 1;
                }
            }
        }

19 Source : PDFConvert.cs
with MIT License
from chen0040

public int gsdll_stdout(IntPtr intGSInstanceHandle, IntPtr strz , int intBytes)
        {
            // If you can think of a more efficient method, please tell me!
            // We need to convert from a byte buffer to a string
            // First we create a byte array of the appropriate size
            byte[] aByte = new byte[intBytes];
            // Then we get the address of the byte array
            GCHandle gcByte = GCHandle.Alloc(aByte, GCHandleType.Pinned);
            IntPtr ptrByte = gcByte.AddrOfPinnedObject();
            // Then we copy the buffer to the byte array
            CopyMemory(ptrByte, strz, (uint)intBytes);
            // Release the address locking
            ptrByte = IntPtr.Zero;
            gcByte.Free();
            // Then we copy the byte array to a string, character by character
            string str = "";
            for (int i = 0; i < intBytes; i++)
            {
                str += (char)aByte[i];
            }
            // Finally we output the message
            //Console.Write(str);
            output.Append(str);
            return intBytes;
            //if (intBytes > 0)
            //{
            //    Console.Write(Marshal.PtrToStringAnsi(strz));
            //}
            //return 0;
        }

19 Source : PDFConvert.cs
with MIT License
from chen0040

public GhostScriptRevision GetRevision()
        {
            // Check revision number of Ghostscript
            int intReturn;
            GS_Revision udtGSRevInfo = new GS_Revision();
            GhostScriptRevision output;
            GCHandle gcRevision;
            gcRevision = GCHandle.Alloc(udtGSRevInfo, GCHandleType.Pinned);
            intReturn = gsapi_revision(ref udtGSRevInfo, 16);
            output.intRevision = udtGSRevInfo.intRevision;
            output.intRevisionDate = udtGSRevInfo.intRevisionDate;
            output.ProductInformation = AnsiZtoString(udtGSRevInfo.strProduct);
            output.CopyrightInformations = AnsiZtoString(udtGSRevInfo.strCopyright);
            gcRevision.Free();
            return output;
        }

19 Source : ARKitSessionSubsystem.cs
with Apache License 2.0
from chenjd

[MonoPInvokeCallback(typeof(NativeApi.OnAsyncConversionCompleteDelegate))]
        static unsafe void OnAsyncConversionComplete(ARWorldMapRequestStatus status, int worldMapId, IntPtr context)
        {
            var handle = GCHandle.FromIntPtr(context);
            var onComplete = (Action<ARWorldMapRequestStatus, ARWorldMap>)handle.Target;

            if (status.IsError())
            {
                onComplete(status, default(ARWorldMap));
            }
            else
            {
                var worldMap = new ARWorldMap(worldMapId);
                onComplete(status, worldMap);
            }

            handle.Free();
        }

19 Source : Button.cs
with MIT License
from chkn

static void OnDispose (void* gcHandlePtr)
		{
			var gcHandle = GCHandle.FromIntPtr ((IntPtr)gcHandlePtr);
			gcHandle.Free ();
		}

19 Source : ManagedSwiftType.cs
with MIT License
from chkn

protected virtual void Dispose (bool disposing)
		{
			if (gch.IsAllocated)
				gch.Free ();
			if (fullMetadata != null) {
				var vwt = fullMetadata->ValueWitnessTable;
				if (vwt != null) {
					fullMetadata->ValueWitnessTable = null;
					Marshal.FreeHGlobal ((IntPtr)vwt);
				}

				Marshal.FreeHGlobal ((IntPtr)fullMetadata);
				fullMetadata = null;
			}
		}

19 Source : SwiftHandle.cs
with MIT License
from chkn

public void Dispose ()
		{
			if (tp.IsOwned)
				swiftType.Destroy (tp.Pointer);
			if (handle.IsAllocated)
				handle.Free ();
			tp = default;
		}

19 Source : BlittableHelper.cs
with zlib License
from ChrisDill

public static bool IsBlittable(this Type type)
        {
            if (type == typeof(decimal))
            {
                return false;
            }
            if (type.IsArray)
            {
                var elementType = type.GetElementType();
                return elementType != null && elementType.IsValueType && IsBlittable(elementType);
            }
            try
            {
                var instance = FormatterServices.GetUninitializedObject(type);
                GCHandle.Alloc(instance, GCHandleType.Pinned).Free();
                return true;
            }
            catch
            {
                return false;
            }
        }

19 Source : DefaultWindowMessageInterceptor.cs
with MIT License
from chromelyapps

protected virtual List<IntPtr> GetAllChildHandles(IntPtr handle)
        {
            var childHandles = new List<IntPtr>();
            GCHandle gcChildhandlesList = GCHandle.Alloc(childHandles);
            IntPtr pointerChildHandlesList = GCHandle.ToIntPtr(gcChildhandlesList);

            try
            {
                var childProc = new EnumWindowProc(EnumWindow);
                EnumChildWindows(handle, childProc, pointerChildHandlesList);
            }
            finally
            {
                gcChildhandlesList.Free();
            }

            return childHandles;
        }

19 Source : NextCommon.cs
with MIT License
from Chykary

protected Result SendSocket(Connection conn, byte[] data, int channelId)
  {    
    Array.Resize(ref data, data.Length + 1);
    data[data.Length - 1] = (byte)channelId;

    GCHandle pinnedArray = GCHandle.Alloc(data, GCHandleType.Pinned);
    IntPtr pData = pinnedArray.AddrOfPinnedObject();
    SendType sendFlag = channelId == Channels.Unreliable ? SendType.Unreliable : SendType.Reliable;
    Result res = conn.SendMessage( pData, data.Length, sendFlag);
    if(res != Result.OK)
    {
      Debug.LogWarning($"Send issue: {res}");
    }

    pinnedArray.Free();
    return res;
  }

19 Source : UwcGetBufferExample.cs
with GNU General Public License v3.0
from CircuitLord

void OnDestroy()
    {
        if (ptr_ != IntPtr.Zero) {
            handle_.Free();
        }
    }

19 Source : UwcLib.cs
with GNU General Public License v3.0
from CircuitLord

public static bool GetWindowPixels(int id, Color32[] colors, int x, int y, int width, int height)
    {
        if (colors.Length < width * height) {
            Debug.LogErrorFormat("colors is smaller than (width * height).", id, x, y, width, height);
            return false;
        }
		var handle = GCHandle.Alloc(colors, GCHandleType.Pinned);
		var ptr = handle.AddrOfPinnedObject();
        if (!GetWindowPixels_Internal(id, ptr, x, y, width, height)) {
            Debug.LogErrorFormat("GetWindowPixels({0}, {1}, {2}, {3}, {4}) failed.", id, x, y, width, height);
            return false;
        }
        handle.Free();
        return true;
    }

19 Source : Lib.cs
with GNU General Public License v3.0
from CircuitLord

public static bool GetPixels(int id, Color32[] colors, int x, int y, int width, int height)
    {
        if (colors.Length < width * height) {
            Debug.LogErrorFormat("colors is small.", id, x, y, width, height);
            return false;
        }
		var handle = GCHandle.Alloc(colors, GCHandleType.Pinned);
		var ptr = handle.AddrOfPinnedObject();
        if (!GetPixels_Internal(id, ptr, x, y, width, height)) {
            Debug.LogErrorFormat("GetPixels({0}, {1}, {2}, {3}, {4}) failed.", id, x, y, width, height);
            return false;
        }
        handle.Free();
        return true;
    }

19 Source : SpeexWrapper.cs
with GNU General Public License v3.0
from ciribob

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

19 Source : AcmStreamHeader.cs
with GNU General Public License v3.0
from ciribob

protected virtual void Dispose(bool disposing)
        {
            if (!disposed)
            {
                //Unprepare();
                sourceBuffer = null;
                destBuffer = null;
                hSourceBuffer.Free();
                hDestBuffer.Free();
            }
            disposed = true;
        }

19 Source : DirectSoundOut.cs
with GNU General Public License v3.0
from ciribob

private void InitializeDirectSound()
        {
            // Open DirectSound
            lock (this.m_LockObject)
            {
                directSound = null;
                DirectSoundCreate(ref device, out directSound, IntPtr.Zero);

                if (directSound != null)
                {
                    // Set Cooperative Level to PRIORITY (priority level can call the SetFormat and Compact methods)
                    directSound.SetCooperativeLevel(GetDesktopWindow(), DirectSoundCooperativeLevel.DSSCL_PRIORITY);

                    // -------------------------------------------------------------------------------------
                    // Create PrimaryBuffer
                    // -------------------------------------------------------------------------------------

                    // Fill BufferDescription for PrimaryBuffer
                    BufferDescription bufferDesc = new BufferDescription();
                    bufferDesc.dwSize = Marshal.SizeOf(bufferDesc);
                    bufferDesc.dwBufferBytes = 0;
                    bufferDesc.dwFlags = DirectSoundBufferCaps.DSBCAPS_PRIMARYBUFFER;
                    bufferDesc.dwReserved = 0;
                    bufferDesc.lpwfxFormat = IntPtr.Zero;
                    bufferDesc.guidAlgo = Guid.Empty;

                    object soundBufferObj;
                    // Create PrimaryBuffer
                    directSound.CreateSoundBuffer(bufferDesc, out soundBufferObj, IntPtr.Zero);
                    primarySoundBuffer = (IDirectSoundBuffer) soundBufferObj;

                    // Play & Loop on the PrimarySound Buffer 
                    primarySoundBuffer.Play(0, 0, DirectSoundPlayFlags.DSBPLAY_LOOPING);

                    // -------------------------------------------------------------------------------------
                    // Create SecondaryBuffer
                    // -------------------------------------------------------------------------------------

                    // A frame of samples equals to Desired Latency
                    samplesFrameSize = MsToBytes(desiredLatency);

                    // Fill BufferDescription for SecondaryBuffer
                    BufferDescription bufferDesc2 = new BufferDescription();
                    bufferDesc2.dwSize = Marshal.SizeOf(bufferDesc2);
                    bufferDesc2.dwBufferBytes = (uint) (samplesFrameSize * 2);
                    bufferDesc2.dwFlags = DirectSoundBufferCaps.DSBCAPS_GETCURRENTPOSITION2
                                          | DirectSoundBufferCaps.DSBCAPS_CTRLPOSITIONNOTIFY
                                          | DirectSoundBufferCaps.DSBCAPS_GLOBALFOCUS
                                          | DirectSoundBufferCaps.DSBCAPS_CTRLVOLUME
                                          | DirectSoundBufferCaps.DSBCAPS_STICKYFOCUS
                                          | DirectSoundBufferCaps.DSBCAPS_GETCURRENTPOSITION2;
                    bufferDesc2.dwReserved = 0;
                    GCHandle handleOnWaveFormat = GCHandle.Alloc(waveFormat, GCHandleType.Pinned); // Ptr to waveFormat
                    bufferDesc2.lpwfxFormat = handleOnWaveFormat.AddrOfPinnedObject(); // set Ptr to waveFormat
                    bufferDesc2.guidAlgo = Guid.Empty;

                    // Create SecondaryBuffer
                    directSound.CreateSoundBuffer(bufferDesc2, out soundBufferObj, IntPtr.Zero);
                    secondaryBuffer = (IDirectSoundBuffer) soundBufferObj;
                    handleOnWaveFormat.Free();

                    // Get effective SecondaryBuffer size
                    BufferCaps dsbCaps = new BufferCaps();
                    dsbCaps.dwSize = Marshal.SizeOf(dsbCaps);
                    secondaryBuffer.GetCaps(dsbCaps);

                    nextSamplesWriteIndex = 0;
                    samplesTotalSize = dsbCaps.dwBufferBytes;
                    samples = new byte[samplesTotalSize];
                    System.Diagnostics.Debug.replacedert(samplesTotalSize == (2 * samplesFrameSize),
                        "Invalid SamplesTotalSize vs SamplesFrameSize");

                    // -------------------------------------------------------------------------------------
                    // Create double buffering notification.
                    // Use DirectSoundNotify at Position [0, 1/2] and Stop Position (0xFFFFFFFF)
                    // -------------------------------------------------------------------------------------
                    IDirectSoundNotify notify = (IDirectSoundNotify) soundBufferObj;

                    frameEventWaitHandle1 = new EventWaitHandle(false, EventResetMode.AutoReset);
                    frameEventWaitHandle2 = new EventWaitHandle(false, EventResetMode.AutoReset);
                    endEventWaitHandle = new EventWaitHandle(false, EventResetMode.AutoReset);

                    DirectSoundBufferPositionNotify[] notifies = new DirectSoundBufferPositionNotify[3];
                    notifies[0] = new DirectSoundBufferPositionNotify();
                    notifies[0].dwOffset = 0;
                    notifies[0].hEventNotify = frameEventWaitHandle1.SafeWaitHandle.DangerousGetHandle();

                    notifies[1] = new DirectSoundBufferPositionNotify();
                    notifies[1].dwOffset = (uint) samplesFrameSize;
                    notifies[1].hEventNotify = frameEventWaitHandle2.SafeWaitHandle.DangerousGetHandle();

                    notifies[2] = new DirectSoundBufferPositionNotify();
                    notifies[2].dwOffset = 0xFFFFFFFF;
                    notifies[2].hEventNotify = endEventWaitHandle.SafeWaitHandle.DangerousGetHandle();

                    notify.SetNotificationPositions(3, notifies);
                }
            }
        }

19 Source : WaveInBuffer.cs
with GNU General Public License v3.0
from ciribob

protected void Dispose(bool disposing)
        {
            if (disposing)
            {
                // free managed resources
            }
            // free unmanaged resources
            if (waveInHandle != IntPtr.Zero)
            {
                WaveInterop.waveInUnprepareHeader(waveInHandle, header, Marshal.SizeOf(header));
                waveInHandle = IntPtr.Zero;
            }
            if (hHeader.IsAllocated)
                hHeader.Free();
            if (hBuffer.IsAllocated)
                hBuffer.Free();
            if (hThis.IsAllocated)
                hThis.Free();
        }

19 Source : WaveOutBuffer.cs
with GNU General Public License v3.0
from ciribob

protected void Dispose(bool disposing)
        {
            if (disposing)
            {
                // free managed resources
            }
            // free unmanaged resources
            if (hHeader.IsAllocated)
                hHeader.Free();
            if (hBuffer.IsAllocated)
                hBuffer.Free();
            if (hThis.IsAllocated)
                hThis.Free();
            if (hWaveOut != IntPtr.Zero)
            {
                lock (waveOutLock)
                {
                    WaveInterop.waveOutUnprepareHeader(hWaveOut, header, Marshal.SizeOf(header));
                }
                hWaveOut = IntPtr.Zero;
            }
        }

19 Source : AppRestartRecoveryNativeMethods.cs
with GNU General Public License v3.0
from CitizensReactor

private static UInt32 InternalRecoveryHandler(IntPtr parameter)
        {
            bool cancelled = false;
            ApplicationRecoveryInProgress(out cancelled);

            GCHandle handle = GCHandle.FromIntPtr(parameter);
            RecoveryData data = handle.Target as RecoveryData;
            data.Invoke();
            handle.Free();

            return (0);
        }

19 Source : MonoUsbTransferContext.cs
with GNU General Public License v3.0
from ClusterM

private void freeTransfer()
        {
            if (mTransfer.IsInvalid || mOwnsTransfer == false) return;
            mTransferCancelEvent.Set();
            mTransferCompleteEvent.WaitOne(200, UsbConstants.EXIT_CONTEXT);
            mTransfer.Free();

            if (mCompleteEventHandle.IsAllocated)
                mCompleteEventHandle.Free();

           
        }

See More Examples