System.Runtime.InteropServices.GCHandle.Alloc(object)

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

114 Examples 7

19 Source : UnityRemoteVideo.cs
with MIT License
from 734843327

void InitializeTextures(UnityARCamera camera)
		{
			int numYBytes = camera.videoParams.yWidth * camera.videoParams.yHeight;
			int numUVBytes = camera.videoParams.yWidth * camera.videoParams.yHeight / 2; //quarter resolution, but two bytes per pixel
			
			m_textureYBytes = new byte[numYBytes];
			m_textureUVBytes = new byte[numUVBytes];
			m_textureYBytes2 = new byte[numYBytes];
			m_textureUVBytes2 = new byte[numUVBytes];
			m_pinnedYArray = GCHandle.Alloc (m_textureYBytes);
			m_pinnedUVArray = GCHandle.Alloc (m_textureUVBytes);
			bTexturesInitialized = true;
		}

19 Source : DSPGraph.cs
with MIT License
from aksyr

public int AddNodeEventHandler<TNodeEvent>(Action<DSPNode, TNodeEvent> handler) where TNodeEvent : unmanaged
        {
            if (handler == null)
                throw new ArgumentNullException(nameof(handler));

            NodeEventCallback callbackWrapper = new NodeEventWrapper<TNodeEvent>(handler).InvokeCallback;
            return RegisterNodeEventHandler<TNodeEvent>(GCHandle.Alloc(callbackWrapper));
        }

19 Source : DSPGraphExtensions.cs
with MIT License
from aksyr

public static GCHandle WrapAction<T>(Action<T> callback, T argument)
        {
            if (callback == null)
                return default;
            void wrapper() => callback(argument);
            return GCHandle.Alloc((Action)wrapper);
        }

19 Source : GvrVideoPlayerTexture.cs
with MIT License
from alanplotko

internal static IntPtr ToIntPtr(System.Object obj) {
    GCHandle handle = GCHandle.Alloc(obj);
    return GCHandle.ToIntPtr(handle);
  }

19 Source : VoiceServer.Events.Native.cs
with MIT License
from AlternateLife

internal void RegisterEvent<T>(Action<T> register, T callback)
        {
            _garbageCollectorHandles.Add(GCHandle.Alloc(callback));

            register(callback);
        }

19 Source : Includer.cs
with MIT License
from amerkoleci

public unsafe void Activate(Options options)
        {
            if (!_includerGCHandle.IsAllocated)
                _includerGCHandle = GCHandle.Alloc(this);
            shaderc_compile_options_set_include_callbacks(options.Handle, shaderc_include_resolve, shaderc_include_result_release, (void*)GCHandle.ToIntPtr(_includerGCHandle));
        }

19 Source : ARKitInterface.cs
with MIT License
from ARUnityBook

void UpdateFrame(UnityARCamera camera)
        {
            if (!m_TexturesInitialized)
            {
                m_CameraWidth = camera.videoParams.yWidth;
                m_CameraHeight = camera.videoParams.yHeight;

                int numYBytes = camera.videoParams.yWidth * camera.videoParams.yHeight;
                int numUVBytes = camera.videoParams.yWidth * camera.videoParams.yHeight / 2; //quarter resolution, but two bytes per pixel

                m_TextureYBytes = new byte[numYBytes];
                m_TextureUVBytes = new byte[numUVBytes];
                m_TextureYBytes2 = new byte[numYBytes];
                m_TextureUVBytes2 = new byte[numUVBytes];
                m_PinnedYArray = GCHandle.Alloc(m_TextureYBytes);
                m_PinnedUVArray = GCHandle.Alloc(m_TextureUVBytes);
                m_TexturesInitialized = true;
            }

            m_PointCloudData = camera.pointCloudData;
            m_LightEstimate.capabilities = LightEstimateCapabilities.AmbientColorTemperature | LightEstimateCapabilities.AmbientIntensity;
            m_LightEstimate.ambientColorTemperature = camera.lightEstimation.ambientColorTemperature;

            // Convert ARKit intensity to Unity intensity
            // ARKit ambient intensity ranges 0-2000
            // Unity ambient intensity ranges 0-8 (for over-bright lights)
            m_LightEstimate.ambientIntensity = camera.lightEstimation.ambientIntensity / 1000f;

			//get display transform matrix sent up from sdk
			m_DisplayTransform.SetColumn(0, camera.displayTransform.column0);
			m_DisplayTransform.SetColumn(1, camera.displayTransform.column1);
			m_DisplayTransform.SetColumn(2, camera.displayTransform.column2);
			m_DisplayTransform.SetColumn(3, camera.displayTransform.column3);
        }

19 Source : GetPrefixBuilder.cs
with MIT License
from Bannerlord-Coop-Team

public static MethodInfo CreateFactoryMethod<TPatchGenerator>(DynamicMethod method)
        {
            var sTypeName = typeof(TPatchGenerator).FullName;
            var sMethodName = method.Name;

            if (!UsedTypeNames.ContainsKey(sTypeName))
            {
                UsedTypeNames[sTypeName] = 0;
            }
            else
            {
                UsedTypeNames[sTypeName] += 1;
                sTypeName += "_" + UsedTypeNames[sTypeName];
            }

            var typeBuilder = ModuleBuilder.DefineType(sTypeName, TypeAttributes.Clreplaced | TypeAttributes.NotPublic);
            var methodBuilder = typeBuilder.DefineMethod(
                sMethodName,
                MethodAttributes.Static | MethodAttributes.Private, CallingConventions.Standard,
                typeof(DynamicMethod),
                new[] {typeof(MethodBase)});

            var il = methodBuilder.GetILGenerator();

            // Push the DynamicMethod to the stack. Unsafe code ahead!
            // https://stackoverflow.com/questions/4989681/place-an-object-on-top-of-stack-in-ilgenerator
            var gcHandle = GCHandle.Alloc(method);
            var pMethod = GCHandle.ToIntPtr(gcHandle);

            if (IntPtr.Size == 4)
                il.Emit(OpCodes.Ldc_I4, pMethod.ToInt32());
            else
                il.Emit(OpCodes.Ldc_I8, pMethod.ToInt64());
            il.Emit(OpCodes.Ldobj, typeof(DynamicMethod));

            il.Emit(OpCodes.Ret);

            // Build the type
            var declaringType = typeBuilder.CreateType();
            var info = declaringType.GetMethod(sMethodName, BindingFlags.Static | BindingFlags.NonPublic);
            return info;
        }

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

public void GetARWorldMapAsync(
            Action<ARWorldMapRequestStatus, ARWorldMap> onComplete)
        {
            var handle = GCHandle.Alloc(onComplete);
            var context = GCHandle.ToIntPtr(handle);

            NativeApi.UnityARKit_createWorldMapRequestWithCallback(s_OnAsyncWorldMapCompleted, context);
        }

19 Source : Button.cs
with MIT License
from chkn

protected override unsafe void InitNativeData (void* handle, Nullability nullability)
		{
			var ctx = GCHandle.ToIntPtr (GCHandle.Alloc (Action));
			using (var lbl = Label.GetSwiftHandle (nullability [0])) {
				var lty = lbl.SwiftType;
				Init (handle, OnActionDel, OnDisposeDel, ctx, lbl.Pointer, lty.Metadata, lty.GetProtocolConformance (SwiftUILib.ViewProtocol));
			}
		}

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 : Space.cs
with MIT License
from codefoco

public IReadOnlyList<SegmentQueryInfo> SegmentQuery(Vect start, Vect end, double radius, int filter)
        {
            var list = new List<SegmentQueryInfo>();
            var gcHandle = GCHandle.Alloc(list);

            NativeMethods.cpSpaceSegmentQuery(space, start, end, radius, (uint)filter, eachSegmentQuery.ToFunctionPointer(), GCHandle.ToIntPtr(gcHandle));

            gcHandle.Free();
            return list;
        }

19 Source : Space.cs
with MIT License
from codefoco

public IReadOnlyList<Shape> BoundBoxQuery(BoundingBox bb, int filter)
        {
            var list = new List<Shape>();

            var gcHandle = GCHandle.Alloc(list);

            NativeMethods.cpSpaceBBQuery(space, bb, (uint)filter, eachBBQuery.ToFunctionPointer(), GCHandle.ToIntPtr(gcHandle));

            gcHandle.Free();
            return list;
        }

19 Source : NativeInterop.cs
with MIT License
from codefoco

public static IntPtr RegisterHandle(object obj)
        {
            var gcHandle = GCHandle.Alloc(obj);
            return GCHandle.ToIntPtr(gcHandle);
        }

19 Source : Space.cs
with MIT License
from codefoco

public IReadOnlyList<PointQueryInfo> PointQuery(Vect point, double maxDistance, int filter)
        {
            var list = new List<PointQueryInfo>();
            var gcHandle = GCHandle.Alloc(list);

            NativeMethods.cpSpacePointQuery(space, point, maxDistance, (uint)filter, eachPointQuery.ToFunctionPointer(), GCHandle.ToIntPtr(gcHandle));

            gcHandle.Free();
            return list;
        }

19 Source : Space.cs
with MIT License
from codefoco

public IReadOnlyList<ContactPointSet> ShapeQuery(Shape shape)
        {
            var list = new List<ContactPointSet>();
            var gcHandle = GCHandle.Alloc(list);

            NativeMethods.cpSpaceShapeQuery(space, shape.Handle, shapeQueryCallback.ToFunctionPointer(), GCHandle.ToIntPtr(gcHandle));

            gcHandle.Free();
            return list;
        }

19 Source : ManagedObject.cs
with MIT License
from Const-me

uint implAddRef()
		{
			int res = Interlocked.Increment( ref nativeRefCounter );
			if( 1 == res )
			{
				Debug.replacedert( !gchManagedObject.IsAllocated );
				// Retain the original user-provided object.
				// This ManagedObject wrapper is retained too, because ManagedWrapper.WrappersCache<I> has a ConditionalWeakTable for that.
				gchManagedObject = GCHandle.Alloc( managed );
			}
			return (uint)res;
		}

19 Source : LlvmRecompiler.cs
with MIT License
from daeken

static ulong FunctionPtr<DelegateT>(DelegateT func) {
			GCHandle.Alloc(func); // TODO: Delete this when the recompiler is destroyed
			return (ulong) Marshal.GetFunctionPointerForDelegate(func);
		}

19 Source : SignalHandler.cs
with MIT License
from daeken

public static void Setup() {
			if(IsWindows) return;
			
			void Set(int sig, SignalDelegate func) {
				GCHandle.Alloc(func);
				signal(sig, 0);
				signal(sig, (ulong) Marshal.GetFunctionPointerForDelegate(func));
			}
			
			Set(4, SigIll); // SIGILL
			Set(5, SigTrap); // SIGTRAP
			Set(6, SigAbort); // SIGABRT
			Set(8, SigFpe); // SIGFPE
			Set(11, SigSegv); // SIGSEGV
		}

19 Source : TypeMapper.cs
with MIT License
from DaniilSokolyuk

[MethodImpl((MethodImplOptions)256 /* AggressiveInlining */)]
		private EmbeddedObject CreateEmbeddedObject(object obj)
		{
			GCHandle objHandle = GCHandle.Alloc(obj);
			IntPtr objPtr = GCHandle.ToIntPtr(objHandle);
			JsValue objValue = JsValue.CreateExternalObject(objPtr, _embeddedObjectFinalizeCallback);

			var embeddedObject = new EmbeddedObject(obj, objValue);

			ProjectFields(embeddedObject);
			ProjectProperties(embeddedObject);
			ProjectMethods(embeddedObject);
			FreezeObject(objValue);

			return embeddedObject;
		}

19 Source : TypeMapper.cs
with MIT License
from DaniilSokolyuk

[MethodImpl((MethodImplOptions)256 /* AggressiveInlining */)]
		private EmbeddedObject CreateEmbeddedFunction(Delegate del)
		{
			JsNativeFunction nativeFunction = (callee, isConstructCall, args, argCount, callbackData) =>
			{
				object[] processedArgs = GetHosreplacedemMemberArguments(args);
#if NET40
				MethodInfo method = del.Method;
#else
				MethodInfo method = del.GetMethodInfo();
#endif
				ParameterInfo[] parameters = method.GetParameters();

				ReflectionHelpers.FixArgumentTypes(ref processedArgs, parameters);

				object result;

				try
				{
					result = del.DynamicInvoke(processedArgs);
				}
				catch (Exception e)
				{
					JsValue undefinedValue = JsValue.Undefined;
					JsValue errorValue = JsErrorHelpers.CreateError(
						string.Format(Strings.Runtime_HostDelegateInvocationFailed, e.Message));
					JsErrorHelpers.SetException(errorValue);

					return undefinedValue;
				}

				JsValue resultValue = MapToScriptType(result);

				return resultValue;
			};

			GCHandle delHandle = GCHandle.Alloc(del);
			IntPtr delPtr = GCHandle.ToIntPtr(delHandle);
			JsValue prototypeValue = JsValue.CreateExternalObject(delPtr, _embeddedObjectFinalizeCallback);

			JsValue functionValue = JsValue.CreateFunction(nativeFunction);
			functionValue.Prototype = prototypeValue;

			var embeddedObject = new EmbeddedObject(del, functionValue,
				new List<JsNativeFunction> { nativeFunction });

			return embeddedObject;
		}

19 Source : TypeMapper.cs
with MIT License
from DaniilSokolyuk

private EmbeddedType CreateEmbeddedType(Type type)
		{
#if NET40
			Type typeInfo = type;
#else
			TypeInfo typeInfo = type.GetTypeInfo();
#endif
			string typeName = type.FullName;
			BindingFlags defaultBindingFlags = ReflectionHelpers.GetDefaultBindingFlags(true);
			ConstructorInfo[] constructors = type.GetConstructors(defaultBindingFlags);

			JsNativeFunction nativeConstructorFunction = (callee, isConstructCall, args, argCount, callbackData) =>
			{
				object result;
				JsValue resultValue;
				object[] processedArgs = GetHosreplacedemMemberArguments(args);

				if (processedArgs.Length == 0 && typeInfo.IsValueType)
				{
					result = Activator.CreateInstance(type);
					resultValue = MapToScriptType(result);

					return resultValue;
				}

				if (constructors.Length == 0)
				{
					JsValue undefinedValue = JsValue.Undefined;
					JsValue errorValue = JsErrorHelpers.CreateError(
						string.Format(Strings.Runtime_HostTypeConstructorNotFound, typeName));
					JsErrorHelpers.SetException(errorValue);

					return undefinedValue;
				}

				var bestFitConstructor = (ConstructorInfo)ReflectionHelpers.GetBestFitMethod(
					constructors, processedArgs);
				if (bestFitConstructor == null)
				{
					JsValue undefinedValue = JsValue.Undefined;
					JsValue errorValue = JsErrorHelpers.CreateReferenceError(
						string.Format(Strings.Runtime_SuitableConstructorOfHostTypeNotFound, typeName));
					JsErrorHelpers.SetException(errorValue);

					return undefinedValue;
				}

				ReflectionHelpers.FixArgumentTypes(ref processedArgs, bestFitConstructor.GetParameters());

				try
				{
					result = bestFitConstructor.Invoke(processedArgs);
				}
				catch (Exception e)
				{
					JsValue undefinedValue = JsValue.Undefined;
					JsValue errorValue = JsErrorHelpers.CreateError(
						string.Format(Strings.Runtime_HostTypeConstructorInvocationFailed, typeName, e.Message));
					JsErrorHelpers.SetException(errorValue);

					return undefinedValue;
				}

				resultValue = MapToScriptType(result);

				return resultValue;
			};

			string embeddedTypeKey = type.replacedemblyQualifiedName;
			GCHandle embeddedTypeKeyHandle = GCHandle.Alloc(embeddedTypeKey);
			IntPtr embeddedTypeKeyPtr = GCHandle.ToIntPtr(embeddedTypeKeyHandle);
			JsValue prototypeValue = JsValue.CreateExternalObject(embeddedTypeKeyPtr,
				_embeddedTypeFinalizeCallback);

			JsValue typeValue = JsValue.CreateFunction(nativeConstructorFunction);
			typeValue.Prototype = prototypeValue;

			var embeddedType = new EmbeddedType(type, typeValue,
				new List<JsNativeFunction> { nativeConstructorFunction });

			ProjectFields(embeddedType);
			ProjectProperties(embeddedType);
			ProjectMethods(embeddedType);
			FreezeObject(typeValue);

			return embeddedType;
		}

19 Source : Monitor.cs
with Apache License 2.0
from deepakkumar1984

public void Install(Executor exe)
        {
            if (exe == null)
                throw new ArgumentNullException(nameof(exe));

            unsafe
            {
                var functionPointer =
                    Marshal.GetFunctionPointerForDelegate(
                        new NativeMethods.ExecutorMonitorCallbackDelegate(executor_callback));
                var gcHandle = GCHandle.Alloc(functionPointer);
                var callbackHandle = GCHandle.Alloc(this);
                var callback = (IntPtr) functionPointer.ToPointer();
                NativeMethods.MXExecutorSetMonitorCallback(exe.Handle, callback, (IntPtr) callbackHandle);
                callbackHandle.Free();
                gcHandle.Free();
            }

            Exes.Add(exe);
        }

19 Source : Function.cs
with Apache License 2.0
from deepakkumar1984

public static (MXNetValue[], TypeCode[], int) MakeMxnetArgs(List<object> args, List<object> temp_args)
        {
            var num_args = args.Count;
            var values = new MXNetValue[num_args];
            var type_codes = new TypeCode[num_args];
            foreach (var _tup_1 in args.Select((_p_1, _p_2) => Tuple.Create(_p_2, _p_1)))
            {
                var i = _tup_1.Item1;
                var arg = _tup_1.Item2;
                if (arg is NDArray)
                {
                    values[i].v_handle = ((NDArray)arg).NativePtr;
                    type_codes[i] = TypeCode.NDARRAYHANDLE;
                }
                else if (arg is ndarray)
                {
                    values[i].v_handle = ((ndarray)arg).NativePtr;
                    type_codes[i] = TypeCode.NDARRAYHANDLE;
                }
                else if (arg is int || arg is long)
                {
                    values[i].v_int64 = (long)arg;
                    type_codes[i] = TypeCode.INT;
                }
                else if (arg is ObjectBase)
                {
                    values[i].v_handle = ((ObjectBase)arg).handle;
                    type_codes[i] = TypeCode.OBJECT_HANDLE;
                }
                else if (arg == null)
                {
                    values[i].v_handle = new IntPtr();
                    type_codes[i] = TypeCode.NULL;
                }
                else if (arg is object)
                {
                    values[i].v_handle = GCHandle.Alloc(arg).AddrOfPinnedObject();
                    type_codes[i] = TypeCode.OBJECT_HANDLE;
                }
                else if (arg is float || arg is double)
                {
                    values[i].v_float64 = (double)arg;
                    type_codes[i] = TypeCode.FLOAT;
                }
                else if (arg is string)
                {
                    unsafe
                    {
                        values[i].v_str = (char*)GCHandle.Alloc(arg).AddrOfPinnedObject();
                        type_codes[i] = TypeCode.STR;
                    }
                }
                //else if (arg is list || arg is tuple || arg is dict)
                //{
                //    arg = _FUNC_CONVERT_TO_NODE(arg);
                //    values[i].v_handle = arg.handle;
                //    type_codes[i] = TypeCode.OBJECT_HANDLE;
                //    temp_args.append(arg);
                //}
                else if (arg is IntPtr)
                {
                    values[i].v_handle = (IntPtr)arg;
                    type_codes[i] = TypeCode.HANDLE;
                }
                else if (arg is DType)
                {
                    unsafe
                    {
                        values[i].v_str = (char*)GCHandle.Alloc(((DType)arg).Name).AddrOfPinnedObject();
                        type_codes[i] = TypeCode.STR;
                    }
                }
                else
                {
                    throw new Exception($"Don't know how to handle type {arg.GetType().Name}");
                }
            }
            return (values, type_codes, num_args);
        }

19 Source : MyWindowHelper.cs
with MIT License
from dimojang

public static List<IntPtr> GetAllChildHandles(IntPtr mainHandle)
        {
            List<IntPtr> childHandles = new List<IntPtr>();

            GCHandle gcChildhandlesList = GCHandle.Alloc(childHandles);
            IntPtr pointerChildHandlesList = GCHandle.ToIntPtr(gcChildhandlesList);

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

            return childHandles;
        }

19 Source : EmitHelper.cs
with MIT License
from Dogwei

public static ILGenerator Calli(this ILGenerator ilGen, DynamicMethod dynamicMethod)
        {
            // 保存引用。
            GCHandle.Alloc(dynamicMethod);

            return ilGen.Calli(
                dynamicMethod.GetFunctionPointer(), 
                dynamicMethod.ReturnType, 
                dynamicMethod.GetParameters().Map(item => item.ParameterType));
        }

19 Source : JsonParserPlugin.cs
with GNU General Public License v2.0
from e2e8

[DllExport]
        public static void Initialize(ref IntPtr data, IntPtr rm)
        {
            data = GCHandle.ToIntPtr(GCHandle.Alloc(new Measure(rm)));
        }

19 Source : ChildWindowBatchEnumerator.cs
with Mozilla Public License 2.0
from ehsan2022002

private List<IntPtr> GetAllChildHandles()
        {
            if (null == LastStepResult)
                LastStepResult = new List<IntPtr>();
            else
                LastStepResult.Clear();
            LastStepResult.Add(_rootHandle);

            foreach (SearchCriteria search in SearchOrder)
            {
                Current = search;

                List<IntPtr> childHandles = new List<IntPtr>();
                GCHandle gcChildhandlesList = GCHandle.Alloc(childHandles);
                IntPtr pointerChildHandlesList = GCHandle.ToIntPtr(gcChildhandlesList);

                foreach (IntPtr handle in LastStepResult)
                {
                    EnumWindowProc childProc = new EnumWindowProc(EnumWindow);
                    EnumChildWindows(handle, childProc, pointerChildHandlesList);
                }

                if (childHandles.Count == 0)
                    break;

                LastStepResult.Clear();
                foreach (IntPtr item in childHandles)
                    LastStepResult.Add(item);
                childHandles.Clear();
                gcChildhandlesList.Free();
            }

            Result.Clear();
            foreach (IntPtr item in LastStepResult)
                Result.Add(item);

            return Result;
        }

19 Source : ChildWindowEnumerator.cs
with Mozilla Public License 2.0
from ehsan2022002

private List<IntPtr> GetAllChildHandles()
        {
            List<IntPtr> childHandles = new List<IntPtr>();

            GCHandle gcChildhandlesList = GCHandle.Alloc(childHandles);
            IntPtr pointerChildHandlesList = GCHandle.ToIntPtr(gcChildhandlesList);

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

            return childHandles;
        }

19 Source : User32.cs
with Mozilla Public License 2.0
from ehsan2022002

public static List<IntPtr> GetChildWindows(IntPtr parent)
        {
            List<IntPtr> result = new List<IntPtr>();
            GCHandle listHandle = GCHandle.Alloc(result);
            try
            {
                EnumWindowProc childProc = new EnumWindowProc(EnumWindow);
                EnumChildWindows(parent, childProc, GCHandle.ToIntPtr(listHandle));
            }
            finally
            {
                if (listHandle.IsAllocated)
                    listHandle.Free();
            }
            return result;
        }

19 Source : NativeHelper.cs
with MIT License
from EomTaeWook

public static IList<Tuple<string,IntPtr>> GetChildHandles(IntPtr mainWindowHandle)
        {
            var childHandles = new List<Tuple<string, IntPtr>>();
            var gcHandle = GCHandle.Alloc(childHandles);
            try
            {
                EnumChildWindows(mainWindowHandle, new EnumWindowProcDelegate((hwnd, lParam) =>
                {
                    var lParamHwnd = GCHandle.FromIntPtr(lParam);
                    if (lParamHwnd.Target == null && lParamHwnd == null)
                        return false;
                    if (lParamHwnd.Target is List<Tuple<string, IntPtr>> list)
                    {
                        var sb = new StringBuilder();
                        GetWindowText(hwnd, sb, GetWindowTextLength(hwnd) + 1);
                        list.Add(Tuple.Create(sb.ToString(), hwnd));
                    }
                    return true;
                }), GCHandle.ToIntPtr(gcHandle));
            }
            finally
            {
                if (gcHandle.IsAllocated)
                    gcHandle.Free();
            }
            return childHandles;
        }

19 Source : GameWindowHooker.cs
with GNU General Public License v3.0
from ErogeHelper

private static IEnumerable<HWND> GetChildWindows(HWND parent)
        {
            List<HWND> result = new();
            var listHandle = GCHandle.Alloc(result);
            try
            {
                static bool childProc(HWND handle, IntPtr pointer)
                {
                    var gch = GCHandle.FromIntPtr(pointer);
                    if (gch.Target is not List<HWND> list)
                    {
                        throw new InvalidCastException("GCHandle Target could not be cast as List<HWND>");
                    }
                    list.Add(handle);
                    return true;
                }
                User32.EnumChildWindows(parent, childProc, GCHandle.ToIntPtr(listHandle));
            }
            finally
            {
                if (listHandle.IsAllocated)
                    listHandle.Free();
            }
            return result;
        }

19 Source : Host.cs
with MIT License
from FabianTerhorst

private static void SetDelegates()
        {
            _executeResource = ExecuteResource;
            _handles.AddFirst(GCHandle.Alloc(_executeResource));
            _executeResourceUnload = ExecuteResourceUnload;
            _handles.AddFirst(GCHandle.Alloc(_executeResourceUnload));
            _stopRuntime = StopRuntime;
            CoreClr_SetResourceLoadDelegates(_executeResource, _executeResourceUnload, _stopRuntime);
        }

19 Source : XA2Buffer.cs
with MIT License
from feliwir

public override unsafe void BufferData<T>(T[] buffer, AudioFormat format)
        {
            int sizeInBytes = sizeof(T) * buffer.Length;

            var handle = GCHandle.Alloc(buffer);
            IntPtr ptr = Marshal.UnsafeAddrOfPinnedArrayElement(buffer, 0);

            BufferData(ptr, sizeInBytes, format);

            handle.Free();
        }

19 Source : MemHelper.cs
with GNU General Public License v3.0
from freezy

public static IntPtr ToIntPtr(object item)
		{
			if (item != null) {
				var gcHandle = GCHandle.Alloc(item);
				return (IntPtr) gcHandle;
			}
			return new IntPtr();
		}

19 Source : MeshUploader.cs
with GNU Lesser General Public License v3.0
from FusedVR

public IntPtr CreatePointerToMarshalledMesh()
            {
                var marshalledMesh = new MarshalledMesh();

                marshalledMesh.vertices = PinAndTrackHandle(vertices);
                marshalledMesh.uvs = PinAndTrackHandle(uvs);

                if (uv2s != null)
                {
                    marshalledMesh.uv2s = PinAndTrackHandle(uv2s);
                }

                marshalledMesh.indices = PinAndTrackHandle(indices);
                marshalledMesh.originEcef = PinAndTrackHandle(originECEF);

                GCHandle handle = GCHandle.Alloc(this);
                marshalledMesh.unpackedMeshHandle = GCHandle.ToIntPtr(handle);
                gcHandles.Add(handle);

                return PinAndTrackHandle(marshalledMesh);
            }

19 Source : TextureLoadHandler.cs
with GNU Lesser General Public License v3.0
from FusedVR

public IntPtr CreatePointerToMarshalledTextureBuffer()
            {
                var marshalled = new MarshalledTextureBuffer();

                marshalled.format = (int)format;
                marshalled.height = height;
                marshalled.width = width;
                marshalled.mipMaps = mipMaps;
                marshalled.sizeInBytes = allocatedBuffer.Length;
                marshalled.data = PinAndTrackHandle(allocatedBuffer);

                GCHandle handle = GCHandle.Alloc(this);
                marshalled.textureBufferHandle = GCHandle.ToIntPtr(handle);
                gcHandles.Add(handle);

                return PinAndTrackHandle(marshalled);
            }

19 Source : MemoryFileSystem.cs
with GNU General Public License v3.0
from HMBSbige

public override IntPtr FileOpen(IntPtr Path)
        {
            string fileName = Help.PtrToStringUTF8(Path);
            if (OnDataLoaded != null)
            {
                DataLoadedEventArgs e = new DataLoadedEventArgs(fileName);
                OnDataLoaded(this, e);
                if (e.Data == null)
                {
                    e.Data = File.ReadAllBytes(fileName);
                    if (e.Data == null)
                    {
                        return IntPtr.Zero;
                    }
                }
                MemoryStream ms = new MemoryStream(e.Data);
                GCHandle handle = GCHandle.Alloc(ms);
                return GCHandle.ToIntPtr(handle);

            }
            return IntPtr.Zero;
        }

19 Source : ARKitInterface.cs
with Apache License 2.0
from holokit

void UpdateFrame(UnityARCamera camera)
        {
            if (!m_TexturesInitialized)
            {
                m_CameraWidth = camera.videoParams.yWidth;
                m_CameraHeight = camera.videoParams.yHeight;

                int numYBytes = camera.videoParams.yWidth * camera.videoParams.yHeight;
                int numUVBytes = camera.videoParams.yWidth * camera.videoParams.yHeight / 2; //quarter resolution, but two bytes per pixel

                m_TextureYBytes = new byte[numYBytes];
                m_TextureUVBytes = new byte[numUVBytes];
                m_TextureYBytes2 = new byte[numYBytes];
                m_TextureUVBytes2 = new byte[numUVBytes];
                m_PinnedYArray = GCHandle.Alloc(m_TextureYBytes);
                m_PinnedUVArray = GCHandle.Alloc(m_TextureUVBytes);
                m_TexturesInitialized = true;
            }

            m_PointCloudData = camera.pointCloudData;
            m_LightEstimate.capabilities = LightEstimateCapabilities.AmbientColorTemperature | LightEstimateCapabilities.AmbientIntensity;
			m_LightEstimate.ambientColorTemperature = camera.lightData.arLightEstimate.ambientColorTemperature;

            // Convert ARKit intensity to Unity intensity
            // ARKit ambient intensity ranges 0-2000
            // Unity ambient intensity ranges 0-8 (for over-bright lights)
			m_LightEstimate.ambientIntensity = camera.lightData.arLightEstimate.ambientIntensity / 1000f;

			//get display transform matrix sent up from sdk
			m_DisplayTransform.SetColumn(0, camera.displayTransform.column0);
			m_DisplayTransform.SetColumn(1, camera.displayTransform.column1);
			m_DisplayTransform.SetColumn(2, camera.displayTransform.column2);
			m_DisplayTransform.SetColumn(3, camera.displayTransform.column3);
        }

19 Source : MessageBoxHelper.cs
with MIT License
from isaacrlevin

public void Prep(Window form)
            {
                NativeMethods.CenterMessageCallBackDelegate callBackDelegate = new NativeMethods.CenterMessageCallBackDelegate(CenterMessageCallBack);
                GCHandle.Alloc(callBackDelegate);

                parentFormHandle = new WindowInteropHelper(form).Handle;
                messageHook = NativeMethods.SetWindowsHookEx(5, callBackDelegate, new IntPtr(NativeMethods.GetWindowLong(parentFormHandle, -6)), NativeMethods.GetCurrentThreadId()).ToInt32();
            }

19 Source : PluginPowershell.cs
with MIT License
from JarateKing

[DllExport]
        public static void Initialize(ref IntPtr data, IntPtr rm)
        {
            data = GCHandle.ToIntPtr(GCHandle.Alloc(new Measure()));
        }

19 Source : KeyboardHook.cs
with MIT License
from joergkrause

protected override void OnStart()
        {
            _hookProc = new KeyboardLowLevelHookProc(HookProc);
            _hookHandle = NativeMethods.SetWindowsHookEx(_hookProc);

            if (_hookHandle.IsInvalid)
            {
                throw new Win32Exception();
            }

            _hookRoot = GCHandle.Alloc(this);
        }

19 Source : ComputeDevice.cs
with GNU Affero General Public License v3.0
from john-h-k

private void RegisterMemoryEventDelegate()
        {
            if (_registered)
            {
                return;
            }
            _registered = true;
            var gcHandle = GCHandle.Alloc(this);
            var context = (void*)GCHandle.ToIntPtr(gcHandle);

            fixed (uint* pCookie = &_vidMemCookie)
            {
                if (Adapter._adapter.TryQueryInterface<IDXGIAdapter3>(out var adapter3))
                {
                    using (adapter3)
                    {
                        IntPtr handle = CreateEventW(null, FALSE, FALSE, null);

                        Guard.ThrowIfFailed(adapter3.Ptr->RegisterVideoMemoryBudgetChangeNotificationEvent(handle, pCookie));

                        IntPtr newHandle;

                        int err = RegisterWaitForSingleObject(
                            &newHandle,
                            handle,
                            &DxgiMemoryInfoChangedCallback,
                            context,
                            INFINITE,
                            0
                        );

                        if (err == 0)
                        {
                            ThrowHelper.ThrowWin32Exception("RegisterWaitForSingleObject failed");
                        }
                    }
                }
                else if (Adapter._adapter.TryQueryInterface<IDXCoreAdapter>(out var adapter))
                {
                    using (adapter)
                    {
                        using UniqueComPtr<IDXCoreAdapterFactory> factory = default;
                        Guard.ThrowIfFailed(adapter.Ptr->GetFactory(factory.Iid, (void**)&factory));

                        Guard.ThrowIfFailed(factory.Ptr->RegisterEventNotification(
                            Adapter.GetAdapterPointer(),
                            DXCoreNotificationType.AdapterBudgetChange,
                            &DxCoreMemoryInfoChangedCallback,
                            context,
                            pCookie
                        ));
                    }
                }
            }
        }

19 Source : GCSyncService.cs
with MIT License
from JohnMasen

public GCHandle SyncWithJsValue(object obj, JavaScriptValue jsValue)
        {
            GCHandle handle = GCHandle.Alloc(obj);
            IntPtr p = GCHandle.ToIntPtr(handle);
            contextSwitch.With(() =>
            {
                JavaScriptContext.SetObjectBeforeCollectCallback(jsValue, p, callback);
                
            });
            return handle;
        }

19 Source : BlazorNewEdgeWebView.cs
with Apache License 2.0
from jspuij

protected override HandleRef BuildWindowCore(HandleRef hwndParent)
        {
            this.ownerThreadId = Thread.CurrentThread.ManagedThreadId;

            var onWebMessageReceivedDelegate = (WebMessageReceivedCallback)this.ReceiveWebMessage;
            this.gcHandlesToFree.Add(GCHandle.Alloc(onWebMessageReceivedDelegate));

            var onErrorMessageDelegate = (ErrorOccuredCallback)this.ReceiveErrorMessage;
            this.gcHandlesToFree.Add(GCHandle.Alloc(onErrorMessageDelegate));

            this.blazorWebView = BlazorWebViewNative_Ctor(hwndParent.Handle, this.UserDataFolder, onWebMessageReceivedDelegate, onErrorMessageDelegate);
            var hwnd = BlazorWebViewNative_GetHWND(this.blazorWebView);
            return new HandleRef(this, hwnd);
        }

19 Source : BlazorNewEdgeWebView.cs
with Apache License 2.0
from jspuij

private void AddCustomScheme(string scheme, ResolveWebResourceDelegate requestHandler)
        {
            // Because of WKWebView limitations, this can only be called during the constructor
            // before the first call to Show. To enforce this, it's private and is only called
            // in response to the constructor options.
            WebResourceRequestedCallback callback = (string url, out int numBytes, out string contentType) =>
            {
                var responseStream = requestHandler(url, out contentType, out Encoding encoding);
                if (responseStream == null)
                {
                    // Webview should preplaced through request to normal handlers (e.g., network)
                    // or handle as 404 otherwise
                    numBytes = 0;
                    return default;
                }

                // Read the stream into memory and serve the bytes
                // In the future, it would be possible to preplaced the stream through into C++
                using (responseStream)
                using (var ms = new MemoryStream())
                {
                    responseStream.CopyTo(ms);

                    numBytes = (int)ms.Position;
                    var buffer = Marshal.AllocCoTaskMem(numBytes);
                    Marshal.Copy(ms.GetBuffer(), 0, buffer, numBytes);
                    return buffer;
                }
            };

            this.gcHandlesToFree.Add(GCHandle.Alloc(callback));
            BlazorWebViewNative_AddCustomScheme(this.blazorWebView, scheme, callback);
        }

19 Source : ClassInjector.cs
with GNU Lesser General Public License v3.0
from kagurazakasanae

private static VoidCtorDelegate CreateEmptyCtor(Type targetType)
        {
            var method = new DynamicMethod("FromIl2CppCtorDelegate", MethodAttributes.Public | MethodAttributes.Static, CallingConventions.Standard, typeof(void), new []{typeof(IntPtr)}, targetType, true);

            var body = method.GetILGenerator();
            
            body.Emit(OpCodes.Ldarg_0);
            body.Emit(OpCodes.Newobj, targetType.GetConstructor(new []{typeof(IntPtr)})!);
            body.Emit(OpCodes.Call, typeof(ClreplacedInjector).GetMethod(nameof(ProcessNewObject))!);
            
            body.Emit(OpCodes.Ret);

            var @delegate = (VoidCtorDelegate) method.CreateDelegate(typeof(VoidCtorDelegate));
            GCHandle.Alloc(@delegate); // pin it forever
            return @delegate;
        }

19 Source : ClassInjector.cs
with GNU Lesser General Public License v3.0
from kagurazakasanae

private static Delegate CreateTrampoline(MethodInfo monoMethod)
        {
            var nativeParameterTypes = new[]{typeof(IntPtr)}.Concat(monoMethod.GetParameters()
                .Select(it => it.ParameterType.NativeType()).Concat(new []{typeof(Il2CppMethodInfo*)})).ToArray();

            var managedParameters = new[] {monoMethod.DeclaringType}.Concat(monoMethod.GetParameters().Select(it => it.ParameterType)).ToArray();

            var method = new DynamicMethod("Trampoline_" + ExtractSignature(monoMethod) + monoMethod.DeclaringType + monoMethod.Name,
                MethodAttributes.Static | MethodAttributes.Public, CallingConventions.Standard,
                monoMethod.ReturnType.NativeType(), nativeParameterTypes,
                monoMethod.DeclaringType, true);

            var signature = new DelegateSupport.MethodSignature(monoMethod, true);
            var delegateType = DelegateSupport.GetOrCreateDelegateType(signature, monoMethod);
            
            var body = method.GetILGenerator();

            body.BeginExceptionBlock();
            
            body.Emit(OpCodes.Ldarg_0);
            body.Emit(OpCodes.Call, typeof(ClreplacedInjectorBase).GetMethod(nameof(ClreplacedInjectorBase.GetMonoObjectFromIl2CppPointer))!);
            body.Emit(OpCodes.Castclreplaced, monoMethod.DeclaringType);
            
            for (var i = 1; i < managedParameters.Length; i++)
            {
                body.Emit(OpCodes.Ldarg, i);
                var parameter = managedParameters[i];
                if (!parameter.IsValueType)
                {
                    if(parameter == typeof(string))
                        body.Emit(OpCodes.Call, typeof(IL2CPP).GetMethod(nameof(IL2CPP.Il2CppStringToManaged))!);
                    else
                        body.Emit(OpCodes.Newobj, parameter.GetConstructor(new []{typeof(IntPtr)})!);
                }
            }
            
            body.Emit(OpCodes.Call, monoMethod);
            if (monoMethod.ReturnType == typeof(void))
            {
                // do nothing
            } else if (monoMethod.ReturnType == typeof(string))
            {
                body.Emit(OpCodes.Call, typeof(IL2CPP).GetMethod(nameof(IL2CPP.ManagedStringToIl2Cpp))!);
            } else if (monoMethod.ReturnType.IsValueType)
            {
                throw new NotImplementedException("Value types are not supported for returns");
            }
            else
            {
                body.Emit(OpCodes.Call, typeof(IL2CPP).GetMethod(nameof(IL2CPP.Il2CppObjectBaseToPtr))!);
            }
            body.Emit(OpCodes.Ret);
            
            var exceptionLocal = body.DeclareLocal(typeof(Exception));
            body.BeginCatchBlock(typeof(Exception));
            body.Emit(OpCodes.Stloc, exceptionLocal);
            body.Emit(OpCodes.Ldstr, "Exception in IL2CPP-to-Managed trampoline, not preplaceding it to il2cpp: ");
            body.Emit(OpCodes.Ldloc, exceptionLocal);
            body.Emit(OpCodes.Callvirt, typeof(object).GetMethod(nameof(ToString))!);
            body.Emit(OpCodes.Call, typeof(string).GetMethod(nameof(string.Concat), new []{typeof(string), typeof(string)})!);
            body.Emit(OpCodes.Call, typeof(LogSupport).GetMethod(nameof(LogSupport.Error))!);
            
            body.EndExceptionBlock();
            
            if (monoMethod.ReturnType != typeof(void))
            {
                body.Emit(OpCodes.Ldc_I4_0);
                body.Emit(OpCodes.Conv_I);
            }
            body.Emit(OpCodes.Ret);

            var @delegate = method.CreateDelegate(delegateType);
            GCHandle.Alloc(@delegate); // pin it forever
            return @delegate;
        }

19 Source : CustomTreeNode.cs
with Apache License 2.0
from KHCmaster

void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
        {
            var handle = GCHandle.Alloc(this);
            var address = GCHandle.ToIntPtr(handle);
            info.AddValue("dataAddress", address);
        }

19 Source : NetVips.cs
with MIT License
from kleisauke

public static List<string> GetEnums()
        {
            var allEnums = new List<string>();
            var handle = GCHandle.Alloc(allEnums);

            IntPtr TypeMap(IntPtr type, IntPtr a, IntPtr b)
            {
                var nickname = TypeName(type);

                var list = (List<string>)GCHandle.FromIntPtr(a).Target;
                list.Add(nickname);

                return Vips.TypeMap(type, TypeMap, a, b);
            }

            try
            {
                Vips.TypeMap(TypeFromName("GEnum"), TypeMap, GCHandle.ToIntPtr(handle), IntPtr.Zero);
            }
            finally
            {
                handle.Free();
            }

            // Sort
            allEnums.Sort();

            return allEnums;
        }

See More Examples