System.IntPtr.ToPointer()

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

778 Examples 7

19 View Source File : IAgileReference.net5.cs
License : MIT License
Project Creator : microsoft

static Vftbl()
            {
                AbiToProjectionVftable = new Vftbl
                {
                    IUnknownVftbl = global::WinRT.Interop.IUnknownVftbl.AbiToProjectionVftbl,
#if !NET
                    _Resolve = Marshal.GetFunctionPointerForDelegate(DelegateCache[0] = new ResolveDelegate(Do_Abi_Resolve)).ToPointer(),
#else
                    _Resolve = (delegate* unmanaged<IntPtr, Guid*, IntPtr*, int>)&Do_Abi_Resolve
#endif
                };
                AbiToProjectionVftablePtr = Marshal.AllocHGlobal(Marshal.SizeOf<Vftbl>());
                Marshal.StructureToPtr(AbiToProjectionVftable, AbiToProjectionVftablePtr, false);
            }

19 View Source File : IAgileReference.netstandard2.0.cs
License : MIT License
Project Creator : microsoft

static Vftbl()
            {
                AbiToProjectionVftable = new Vftbl
                {
                    IUnknownVftbl = global::WinRT.Interop.IUnknownVftbl.AbiToProjectionVftbl,

                    _Resolve = Marshal.GetFunctionPointerForDelegate(DelegateCache[0] = new ResolveDelegate(Do_Abi_Resolve)).ToPointer(),

                };
                AbiToProjectionVftablePtr = Marshal.AllocHGlobal(Marshal.SizeOf<Vftbl>());
                Marshal.StructureToPtr(AbiToProjectionVftable, AbiToProjectionVftablePtr, false);
            }

19 View Source File : IMarshal.cs
License : MIT License
Project Creator : microsoft

static Vftbl()
            {
#if !NET
                AbiToProjectionVftable = new Vftbl
                {
                    IUnknownVftbl = global::WinRT.Interop.IUnknownVftbl.AbiToProjectionVftbl,
                    _GetUnmarshalClreplaced_0 = Marshal.GetFunctionPointerForDelegate(DelegateCache[0] = new IMarshal_Delegates.GetUnmarshalClreplaced_0(Do_Abi_GetUnmarshalClreplaced_0)).ToPointer(),
                    _GetMarshalSizeMax_1 = Marshal.GetFunctionPointerForDelegate(DelegateCache[1] = new IMarshal_Delegates.GetMarshalSizeMax_1(Do_Abi_GetMarshalSizeMax_1)).ToPointer(),
                    _MarshalInterface_2 = Marshal.GetFunctionPointerForDelegate(DelegateCache[2] = new IMarshal_Delegates.MarshalInterface_2(Do_Abi_MarshalInterface_2)).ToPointer(),
                    _UnmarshalInterface_3 = Marshal.GetFunctionPointerForDelegate(DelegateCache[3] = new IMarshal_Delegates.UnmarshalInterface_3(Do_Abi_UnmarshalInterface_3)).ToPointer(),
                    _ReleaseMarshalData_4 = Marshal.GetFunctionPointerForDelegate(DelegateCache[4] = new IMarshal_Delegates.ReleaseMarshalData_4(Do_Abi_ReleaseMarshalData_4)).ToPointer(),
                    _DisconnectObject_5 = Marshal.GetFunctionPointerForDelegate(DelegateCache[5] = new IMarshal_Delegates.DisconnectObject_5(Do_Abi_DisconnectObject_5)).ToPointer(),
                };
                AbiToProjectionVftablePtr = Marshal.AllocHGlobal(Marshal.SizeOf<Vftbl>());
                Marshal.StructureToPtr(AbiToProjectionVftable, AbiToProjectionVftablePtr, false);
#else
                AbiToProjectionVftablePtr = ComWrappersSupport.AllocateVtableMemory(typeof(Vftbl), Marshal.SizeOf<global::WinRT.Interop.IUnknownVftbl>() + sizeof(IntPtr) * 6);
                (*(Vftbl*)AbiToProjectionVftablePtr) = new Vftbl
                {
                    IUnknownVftbl = global::WinRT.Interop.IUnknownVftbl.AbiToProjectionVftbl,
                    GetUnmarshalClreplaced_0 = &Do_Abi_GetUnmarshalClreplaced_0,
                    GetMarshalSizeMax_1 = &Do_Abi_GetMarshalSizeMax_1,
                    MarshalInterface_2 = &Do_Abi_MarshalInterface_2,
                    UnmarshalInterface_3 = &Do_Abi_UnmarshalInterface_3,
                    ReleaseMarshalData_4 = &Do_Abi_ReleaseMarshalData_4,
                    DisconnectObject_5 = &Do_Abi_DisconnectObject_5
                };
#endif
            }

19 View Source File : IWeakReferenceSource.netstandard2.0.cs
License : MIT License
Project Creator : microsoft

static Vftbl()
            {
                AbiToProjectionVftable = new Vftbl
                {
                    IUnknownVftbl = global::WinRT.Interop.IUnknownVftbl.AbiToProjectionVftbl,
                    _GetWeakReference = Marshal.GetFunctionPointerForDelegate(DelegateCache[0] = new GetWeakReferenceDelegate(Do_Abi_GetWeakReference)).ToPointer(),
                };
                AbiToProjectionVftablePtr = Marshal.AllocHGlobal(Marshal.SizeOf<Vftbl>());
                Marshal.StructureToPtr(AbiToProjectionVftable, AbiToProjectionVftablePtr, false);
            }

19 View Source File : IWeakReferenceSource.netstandard2.0.cs
License : MIT License
Project Creator : microsoft

static Vftbl()
            {
                AbiToProjectionVftable = new Vftbl
                {
                    IUnknownVftbl = global::WinRT.Interop.IUnknownVftbl.AbiToProjectionVftbl,
                    _Resolve = Marshal.GetFunctionPointerForDelegate(DelegateCache[0] = new ResolveDelegate(Do_Abi_Resolve)).ToPointer(),
                };
                AbiToProjectionVftablePtr = Marshal.AllocHGlobal(Marshal.SizeOf<Vftbl>());
                Marshal.StructureToPtr(AbiToProjectionVftable, AbiToProjectionVftablePtr, false);
            }

19 View Source File : DataErrorsChangedEventArgs.cs
License : MIT License
Project Creator : microsoft

public static unsafe void CopyManaged(global::System.ComponentModel.DataErrorsChangedEventArgs o, IntPtr dest)
        {
            using var objRef = CreateMarshaler(o);
            *(IntPtr*)dest.ToPointer() = objRef?.GetRef() ?? IntPtr.Zero;
        }

19 View Source File : IDisposable.netstandard2.0.cs
License : MIT License
Project Creator : microsoft

static unsafe Vftbl()
            {
                AbiToProjectionVftable = new Vftbl
                {
                    IInspectableVftbl = global::WinRT.IInspectable.Vftbl.AbiToProjectionVftable,

                    _Close_0 = Marshal.GetFunctionPointerForDelegate(closeDelegate = Do_Abi_Close_0).ToPointer()

                };
                var nativeVftbl = (IntPtr*)ComWrappersSupport.AllocateVtableMemory(typeof(Vftbl), Marshal.SizeOf<global::WinRT.IInspectable.Vftbl>() + sizeof(IntPtr) * 1);
                Marshal.StructureToPtr(AbiToProjectionVftable, (IntPtr)nativeVftbl, false);
                AbiToProjectionVftablePtr = (IntPtr)nativeVftbl;
            }

19 View Source File : INotifyDataErrorInfo.netstandard2.0.cs
License : MIT License
Project Creator : microsoft

static unsafe Vftbl()
            {
                AbiToProjectionVftablePtr = ComWrappersSupport.AllocateVtableMemory(typeof(Vftbl), Marshal.SizeOf<global::WinRT.IInspectable.Vftbl>() + sizeof(IntPtr) * 4);
                (*(Vftbl*)AbiToProjectionVftablePtr) = new Vftbl
                {
                    IInspectableVftbl = global::WinRT.IInspectable.Vftbl.AbiToProjectionVftable,
#if !NET
                    _get_HasErrors_0 = (void*)Marshal.GetFunctionPointerForDelegate(DelegateCache[0] = new INotifyDataErrorInfo_Delegates.get_HasErrors_0(Do_Abi_get_HasErrors_0)).ToPointer(),
                    _add_ErrorsChanged_1 = (void*)Marshal.GetFunctionPointerForDelegate(DelegateCache[1] = new INotifyDataErrorInfo_Delegates.add_ErrorsChanged_1(Do_Abi_add_ErrorsChanged_1)).ToPointer(),
                    _remove_ErrorsChanged_2 = (void*)Marshal.GetFunctionPointerForDelegate(DelegateCache[2] = new INotifyDataErrorInfo_Delegates.remove_ErrorsChanged_2(Do_Abi_remove_ErrorsChanged_2)).ToPointer(),
                    _GetErrors_3 = (void*)Marshal.GetFunctionPointerForDelegate(DelegateCache[3] = new INotifyDataErrorInfo_Delegates.GetErrors_3(Do_Abi_GetErrors_3)).ToPointer()
#else
                    get_HasErrors_0 = &Do_Abi_get_HasErrors_0,
                    add_ErrorsChanged_1 = &Do_Abi_add_ErrorsChanged_1,
                    remove_ErrorsChanged_2 = &Do_Abi_remove_ErrorsChanged_2,
                    GetErrors_3 = &Do_Abi_GetErrors_3
#endif
                };
            }

19 View Source File : IReferenceArray.net5.cs
License : MIT License
Project Creator : microsoft

public static unsafe void CopyManaged(object o, IntPtr dest)
        {
            using var objRef = CreateMarshaler(o);
            *(IntPtr*)dest.ToPointer() = objRef?.GetRef() ?? IntPtr.Zero;
        }

19 View Source File : IStringable.cs
License : MIT License
Project Creator : microsoft

static unsafe ManagedIStringableVftbl()
        {
            AbiToProjectionVftable = new ManagedIStringableVftbl
            {
                IInspectableVftbl = global::WinRT.IInspectable.Vftbl.AbiToProjectionVftable,
#if !NET
                _ToString_0 = Marshal.GetFunctionPointerForDelegate(delegateCache = Do_Abi_ToString_0).ToPointer()
#else
                _ToString_0 = (delegate* unmanaged<IntPtr, IntPtr*, int>)&Do_Abi_ToString_0
#endif
            };
            var nativeVftbl = (IntPtr*)ComWrappersSupport.AllocateVtableMemory(typeof(ManagedIStringableVftbl), Marshal.SizeOf<global::WinRT.IInspectable.Vftbl>() + sizeof(IntPtr) * 1);
            Marshal.StructureToPtr(AbiToProjectionVftable, (IntPtr)nativeVftbl, false);
            AbiToProjectionVftablePtr = (IntPtr)nativeVftbl;
        }

19 View Source File : KeyValuePair.cs
License : MIT License
Project Creator : microsoft

internal static unsafe void CopyManaged(global::System.Collections.Generic.KeyValuePair<K, V> o, IntPtr dest)
        {
            using var objRef = CreateMarshaler(o);
            *(IntPtr*)dest.ToPointer() = objRef?.GetRef() ?? IntPtr.Zero;
        }

19 View Source File : NotifyCollectionChangedEventArgs.cs
License : MIT License
Project Creator : microsoft

public static unsafe void CopyManaged(global::System.Collections.Specialized.NotifyCollectionChangedEventArgs o, IntPtr dest)
        {
            using var objRef = CreateMarshaler(o);
            *(IntPtr*)dest.ToPointer() = objRef?.GetRef() ?? IntPtr.Zero;
        }

19 View Source File : PropertyChangedEventArgs.cs
License : MIT License
Project Creator : microsoft

public static unsafe void CopyManaged(global::System.ComponentModel.PropertyChangedEventArgs o, IntPtr dest)
        {
            using var objRef = CreateMarshaler(o);
            *(IntPtr*)dest.ToPointer() = objRef?.GetRef() ?? IntPtr.Zero;
        }

19 View Source File : SystemTypes.cs
License : MIT License
Project Creator : microsoft

public static unsafe void CopyAbi(Marshaler arg, IntPtr dest) =>
            *(TimeSpan*)dest.ToPointer() = GetAbi(arg);

19 View Source File : SystemTypes.cs
License : MIT License
Project Creator : microsoft

public static unsafe void CopyManaged(global::System.TimeSpan arg, IntPtr dest) =>
            *(TimeSpan*)dest.ToPointer() = FromManaged(arg);

19 View Source File : SystemTypes.cs
License : MIT License
Project Creator : microsoft

public static unsafe void CopyAbi(Marshaler arg, IntPtr dest) =>
            *(DateTimeOffset*)dest.ToPointer() = GetAbi(arg);

19 View Source File : SystemTypes.cs
License : MIT License
Project Creator : microsoft

public static unsafe void CopyManaged(global::System.DateTimeOffset arg, IntPtr dest) =>
            *(DateTimeOffset*)dest.ToPointer() = FromManaged(arg);

19 View Source File : SystemTypes.cs
License : MIT License
Project Creator : microsoft

public static unsafe void CopyAbi(Marshaler arg, IntPtr dest) =>
            *(Exception*)dest.ToPointer() = GetAbi(arg);

19 View Source File : SystemTypes.cs
License : MIT License
Project Creator : microsoft

public static unsafe void CopyManaged(global::System.Exception arg, IntPtr dest) =>
            *(Exception*)dest.ToPointer() = FromManaged(arg);

19 View Source File : Type.cs
License : MIT License
Project Creator : microsoft

public static unsafe void CopyAbi(Marshaler arg, IntPtr dest) =>
            *(Type*)dest.ToPointer() = GetAbi(arg);

19 View Source File : Type.cs
License : MIT License
Project Creator : microsoft

public static unsafe void CopyManaged(global::System.Type arg, IntPtr dest) =>
            *(Type*)dest.ToPointer() = FromManaged(arg);

19 View Source File : Uri.cs
License : MIT License
Project Creator : microsoft

public static unsafe void CopyManaged(global::System.Uri o, IntPtr dest)
        {
            using var objRef = CreateMarshaler(o);
            *(IntPtr*)dest.ToPointer() = objRef?.GetRef() ?? IntPtr.Zero;
        }

19 View Source File : FundamentalMarshalers.cs
License : MIT License
Project Creator : microsoft

public static unsafe void CopyAbi(bool value, IntPtr dest) => *(byte*)dest.ToPointer() = GetAbi(value).value;

19 View Source File : FundamentalMarshalers.cs
License : MIT License
Project Creator : microsoft

public static unsafe void CopyManaged(bool arg, IntPtr dest) => *(byte*)dest.ToPointer() = FromManaged(arg).value;

19 View Source File : FundamentalMarshalers.cs
License : MIT License
Project Creator : microsoft

public static unsafe void CopyAbi(char value, IntPtr dest) => *(ushort*)dest.ToPointer() = GetAbi(value).value;

19 View Source File : FundamentalMarshalers.cs
License : MIT License
Project Creator : microsoft

public static unsafe void CopyManaged(char arg, IntPtr dest) => *(ushort*)dest.ToPointer() = FromManaged(arg).value;

19 View Source File : ObjectReference.cs
License : MIT License
Project Creator : microsoft

public unsafe TInterface AsInterface<TInterface>()
        {
            if (typeof(TInterface).GetCustomAttribute(typeof(System.Runtime.InteropServices.ComImportAttribute)) is object)
            {
                Guid iid = typeof(TInterface).GUID;
                Marshal.ThrowExceptionForHR(VftblIUnknown.QueryInterface(ThisPtr, ref iid, out IntPtr comPtr));
                try
                {
                    return (TInterface)Marshal.GetObjectForIUnknown(comPtr);
                }
                finally
                {
                    var vftblPtr = Unsafe.AsRef<WinRT.VftblPtr>(comPtr.ToPointer());
                    var vftblIUnknown = Marshal.PtrToStructure<WinRT.Interop.IUnknownVftbl>(vftblPtr.Vftbl);
                    vftblIUnknown.Release(comPtr);
                }
            }

#if !NET
            return (TInterface)typeof(TInterface).GetHelperType().GetConstructor(new[] { typeof(IObjectReference) }).Invoke(new object[] { this });
#else
            return (TInterface)(object)new WinRT.IInspectable(this);
#endif
        }

19 View Source File : ObjectReference.cs
License : MIT License
Project Creator : microsoft

private static unsafe T GetVtable(IntPtr thisPtr)
        {
            var vftblPtr = Unsafe.AsRef<VftblPtr>(thisPtr.ToPointer());
            T vftblT;
            // With our vtable types, the generic vtables will have System.Delegate fields
            // and the non-generic types will have only void* fields.
            // On .NET 5, we can use RuntimeHelpers.IsReferenceorContainsReferences
            // to disambiguate between generic and non-generic vtables since it's a JIT-time constant.
            // Since it is a JIT time constant, this function will be branchless on .NET 5.
            // On .NET Standard 2.0, the IsReferenceOrContainsReferences method does not exist,
            // so we instead fall back to typeof(T).IsGenericType, which sadly is not a JIT-time constant.
#if !NET
            if (typeof(T).IsGenericType)
#else
            if (RuntimeHelpers.IsReferenceOrContainsReferences<T>())
#endif
            {
                vftblT = (T)typeof(T).GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.CreateInstance, null, new[] { typeof(IntPtr) }, null).Invoke(new object[] { thisPtr });
            }
            else
            {
                vftblT = Unsafe.AsRef<T>(vftblPtr.Vftbl.ToPointer());
            }
            return vftblT;
        }

19 View Source File : modules.cs
License : MIT License
Project Creator : microsoft

private void InitDebugAttributes()
        {
            ICorDebug.IMetadataImport metadata = GetMetadataImport();
            if (metadata == null)
            {
                _debugMode = DebuggableAttribute.DebuggingModes.None;
                return;
            }

            try
            {
                IntPtr data;
                uint cbData;
                int hr = metadata.GetCustomAttributeByName(0x20000001, "System.Diagnostics.DebuggableAttribute", out data, out cbData);
                if (hr != 0 || cbData <= 4)
                {
                    _debugMode = DebuggableAttribute.DebuggingModes.None;
                    return;
                }

                unsafe
                {
                    byte* b = (byte*)data.ToPointer();
                    UInt16 opt = b[2];
                    UInt16 dbg = b[3];

                    _debugMode = (System.Diagnostics.DebuggableAttribute.DebuggingModes)((dbg << 8) | opt);
                }
            }
            catch (SEHException)
            {
                _debugMode = DebuggableAttribute.DebuggingModes.None;
            }
        }

19 View Source File : YuvUtils.cs
License : MIT License
Project Creator : microsoft

public static uint CopyI420FrameToNv12Buffer(IntPtr dataY, IntPtr dataU, IntPtr dataV, int strideY, int strideU, int strideV, uint width, uint height, byte[] buffer)
        {
            uint numBlocks = width * height / 8;

            unsafe
            {
                byte* ptrY = (byte*)dataY.ToPointer();
                byte* ptrU = (byte*)dataU.ToPointer();
                byte* ptrV = (byte*)dataV.ToPointer();

                fixed (byte* ptrBuffer = buffer)
                {
                    byte* dst = ptrBuffer;

                    // Copy 8 Y values
                    //for (int i = 0; i < numBlocks; ++i)
                    //{
                    //    *dst++ = *ptrY++;
                    //    *dst++ = *ptrY++;
                    //    *dst++ = *ptrY++;
                    //    *dst++ = *ptrY++;
                    //    *dst++ = *ptrY++;
                    //    *dst++ = *ptrY++;
                    //    *dst++ = *ptrY++;
                    //    *dst++ = *ptrY++;
                    //}
                    {
                        // Optimized : 8 bytes at a time
                        ulong* dstUlong = (ulong*)dst;
                        ulong* srcUlong = (ulong*)ptrY;
                        for (uint i = 0; i < numBlocks; ++i)
                        {
                            *dstUlong++ = *srcUlong++;
                        }
                        dst = (byte*)dstUlong;
                    }

                    // Copy UVUV values
                    for (int i = 0; i < numBlocks; ++i)
                    {
                        *dst++ = *ptrU++;
                        *dst++ = *ptrV++;
                        *dst++ = *ptrU++;
                        *dst++ = *ptrV++;
                    }
                }
            }

            return (numBlocks * 12); // == (width * height * 3 / 2)
        }

19 View Source File : YuvUtils.cs
License : MIT License
Project Creator : microsoft

public static void CopyYuvToBufferAsRgb(IntPtr dataY, IntPtr dataU, IntPtr dataV, int strideY, int strideU, int strideV, uint width, uint height, byte[] buffer)
        {
            unsafe
            {
                byte* ptrY = (byte*)dataY.ToPointer();
                byte* ptrU = (byte*)dataU.ToPointer();
                byte* ptrV = (byte*)dataV.ToPointer();
                int srcOffsetY = 0;
                int srcOffsetU = 0;
                int srcOffsetV = 0;
                int destOffset = 0;
                for (int i = 0; i < height; i++)
                {
                    srcOffsetY = i * strideY;
                    srcOffsetU = (i / 2) * strideU;
                    srcOffsetV = (i / 2) * strideV;
                    destOffset = i * (int)width * 4;
                    for (int j = 0; j < width; j += 2)
                    {
                        {
                            byte y = ptrY[srcOffsetY];
                            byte u = ptrU[srcOffsetU];
                            byte v = ptrV[srcOffsetV];
                            srcOffsetY++;
                            srcOffsetU++;
                            srcOffsetV++;
                            destOffset += 4;
                            Vector3 yuvF = new Vector3(y / 255.0f, u / 255.0f, v / 255.0f);
                            Vector3 rgbF = Yuv2rgb(yuvF);
                            byte r = (byte)(rgbF.X * 255.0f);
                            byte g = (byte)(rgbF.Y * 255.0f);
                            byte b = (byte)(rgbF.Z * 255.0f);
                            buffer[destOffset] = r;
                            buffer[destOffset + 1] = g;
                            buffer[destOffset + 2] = b;
                            buffer[destOffset + 3] = 0xff;

                            // use same u, v values
                            byte y2 = ptrY[srcOffsetY];
                            srcOffsetY++;
                            destOffset += 4;
                            Vector3 yuv2F = new Vector3(y2 / 255.0f, u / 255.0f, v / 255.0f);
                            Vector3 rgb2F = Yuv2rgb(yuv2F);
                            byte r2 = (byte)(rgb2F.X * 255.0f);
                            byte g2 = (byte)(rgb2F.Y * 255.0f);
                            byte b2 = (byte)(rgb2F.Z * 255.0f);
                            buffer[destOffset] = r2;
                            buffer[destOffset + 1] = g2;
                            buffer[destOffset + 2] = b2;
                            buffer[destOffset + 3] = 0xff;
                        }
                    }
                }
            }
        }

19 View Source File : YuvUtils.cs
License : MIT License
Project Creator : microsoft

public static void CopyYuvToBuffer(IntPtr dataY, IntPtr dataU, IntPtr dataV, int strideY, int strideU, int strideV, uint width, uint height, byte[] buffer)
        {
            unsafe
            {
                byte* ptrY = (byte*)dataY.ToPointer();
                byte* ptrU = (byte*)dataU.ToPointer();
                byte* ptrV = (byte*)dataV.ToPointer();
                int srcOffsetY = 0;
                int srcOffsetU = 0;
                int srcOffsetV = 0;
                int destOffset = 0;
                for (int i = 0; i < height; i++)
                {
                    srcOffsetY = i * strideY;
                    srcOffsetU = (i / 2) * strideU;
                    srcOffsetV = (i / 2) * strideV;
                    destOffset = i * (int)width * 4;
                    for (int j = 0; j < width; j += 2)
                    {
                        {
                            byte y = ptrY[srcOffsetY];
                            byte u = ptrU[srcOffsetU];
                            byte v = ptrV[srcOffsetV];
                            srcOffsetY++;
                            srcOffsetU++;
                            srcOffsetV++;
                            destOffset += 4;
                            buffer[destOffset] = y;
                            buffer[destOffset + 1] = u;
                            buffer[destOffset + 2] = v;
                            buffer[destOffset + 3] = 0xff;

                            // use same u, v values
                            byte y2 = ptrY[srcOffsetY];
                            srcOffsetY++;
                            destOffset += 4;
                            buffer[destOffset] = y2;
                            buffer[destOffset + 1] = u;
                            buffer[destOffset + 2] = v;
                            buffer[destOffset + 3] = 0xff;
                        }
                    }
                }
            }
        }

19 View Source File : VideoFrame.cs
License : MIT License
Project Creator : microsoft

public void CopyTo(byte[] buffer)
        {
            unsafe
            {
                fixed (void* ptr = buffer)
                {
                    // Destination buffer is packed and contiguous
                    ulong dstSizeYA = (ulong)width * height;
                    ulong dstSizeUV = dstSizeYA / 4;
                    int dstStrideYA = (int)width;
                    int dstStrideUV = dstStrideYA / 2;

                    // Note : System.Buffer.MemoryCopy() essentially does the same (without stride), but gets transpiled by IL2CPP
                    // into the C++ corresponding to the IL instead of a single memcpy() call. This results in a large overhead,
                    // especially in Debug config where one can lose 5-10 FPS just because of this.
                    void* dst = ptr;
                    Utils.MemCpyStride(dst, dstStrideYA, (void*)dataY, strideY, (int)width, (int)height);
                    dst = (void*)((ulong)dst + dstSizeYA);
                    Utils.MemCpyStride(dst, dstStrideUV, (void*)dataU, strideU, (int)width / 2, (int)height / 2);
                    dst = (void*)((ulong)dst + dstSizeUV);
                    Utils.MemCpyStride(dst, dstStrideUV, (void*)dataV, strideV, (int)width / 2, (int)height / 2);
                    if (dataA.ToPointer() != null)
                    {
                        dst = (void*)((ulong)dst + dstSizeUV);
                        Utils.MemCpyStride(dst, dstStrideYA, (void*)dataA, strideA, (int)width, (int)height);
                    }
                }
            }
        }

19 View Source File : YuvUtils.cs
License : MIT License
Project Creator : microsoft

public unsafe static uint CopyI420FrameToI420Buffer(IntPtr dataY, IntPtr dataU, IntPtr dataV, int strideY, int strideU, int strideV, uint width, uint height, byte[] buffer)
        {
            uint pixelCount = width * height;
            uint byteSize = (pixelCount * 12 / 8);

            bool hasCompactY = (strideY == width);
            bool hasCompactU = (strideU == width / 2);
            bool hasCompactV = (strideV == width / 2);
            bool hreplacedequentialYU = (dataU.ToInt64() == dataY.ToInt64() + pixelCount);
            bool hreplacedequentialUV = (dataV.ToInt64() == dataU.ToInt64() + pixelCount / 4);

            // Fast path - compact layout
            if (hasCompactY && hasCompactU && hasCompactV && hreplacedequentialYU && hreplacedequentialUV)
            {
                Marshal.Copy(dataY, buffer, 0, (int)byteSize);
                return byteSize;
            }

            // Slow path - individual copies
            if (hasCompactY && hasCompactU && hasCompactV)
            {
                // "Fast-slow" path - still compact buffers, just not sequential
                int yByteSize = (int)pixelCount;
                int uvByteSize = (int)(pixelCount / 4);
                Marshal.Copy(dataY, buffer, 0, yByteSize);
                Marshal.Copy(dataU, buffer, yByteSize, uvByteSize);
                Marshal.Copy(dataV, buffer, yByteSize + uvByteSize, uvByteSize);
            }
            else
            {
                // Really slow path - copy each row byte by byte
                fixed (byte* ptrBuffer = buffer)
                {
                    byte* dst = ptrBuffer;
                    byte* src;
                    uint yWidth = width;
                    uint yHeight = height;
                    uint uvWidth = width / 2;
                    uint uvHeight = height / 2;

                    // Y
                    src = (byte*)dataY.ToPointer();
                    for (uint j = 0; j < yHeight; ++j)
                    {
                        byte* rowSrc = src;
                        for (uint i = 0; i < yWidth; ++i)
                        {
                            *dst++ = *rowSrc++;
                        }
                        src += strideY;
                    }

                    // U
                    src = (byte*)dataU.ToPointer();
                    for (uint j = 0; j < uvHeight; ++j)
                    {
                        byte* rowSrc = src;
                        for (uint i = 0; i < uvWidth; ++i)
                        {
                            *dst++ = *rowSrc++;
                        }
                        src += strideU;
                    }

                    // V
                    src = (byte*)dataV.ToPointer();
                    for (uint j = 0; j < uvHeight; ++j)
                    {
                        byte* rowSrc = src;
                        for (uint i = 0; i < uvWidth; ++i)
                        {
                            *dst++ = *rowSrc++;
                        }
                        src += strideV;
                    }
                }
            }

            return byteSize;
        }

19 View Source File : Snapshot.cs
License : Microsoft Public License
Project Creator : microsoft

unsafe private System.Drawing.Bitmap CreateBitmapFromSnapshot()
        {
            System.Drawing.Bitmap temp = new Bitmap(Width, Height, PixelFormat.Format32bppArgb);

            Rectangle bounds = new Rectangle(Point.Empty, temp.Size);
            BitmapData bitmapData = temp.LockBits(bounds, ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb);
            Byte* pBase = (Byte*)bitmapData.Scan0.ToPointer();

            for (int row = 0; row < Height; row++)
            {
                for (int column = 0; column < Width; column++)
                {
                    // The active implementation is the faster, but unsafe alternative to setpixel API:
                    //    temp.SetPixel(column,row,buffer[row, column]);

                    PixelData* pixelDataAddress = (PixelData*)(pBase + row * Width * sizeof(PixelData) + column * sizeof(PixelData));
                    pixelDataAddress->A = buffer[row, column].A;
                    pixelDataAddress->R = buffer[row, column].R;
                    pixelDataAddress->G = buffer[row, column].G;
                    pixelDataAddress->B = buffer[row, column].B;
                }
            }
            temp.UnlockBits(bitmapData);
            return temp;
        }

19 View Source File : Snapshot4.cs
License : Microsoft Public License
Project Creator : microsoft

unsafe private System.Drawing.Bitmap CreateBitmapFromSnapshot()
        {
            System.Drawing.Bitmap temp = new Bitmap(Width, Height, PixelFormat.Format32bppArgb);

            Rectangle bounds = new Rectangle(Point.Empty, temp.Size);
            BitmapData bitmapData = temp.LockBits(bounds, ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb);
            Byte* pBase = (Byte*)bitmapData.Scan0.ToPointer();
            int thisHeight = Height;
            int thisWidth = Width;
            Parallel.For(0, thisHeight, (row) =>
            {
                for (int column = 0; column < thisWidth; column++)
                {
                    // The active implementation is the faster, but unsafe alternative to setpixel API:
                    //    temp.SetPixel(column,row,buffer[row, column]);

                    PixelData* pixelDataAddress = (PixelData*)(pBase + row * thisWidth * sizeof(PixelData) + column * sizeof(PixelData));
                    pixelDataAddress->A = buffer[row, column].A;
                    pixelDataAddress->R = buffer[row, column].R;
                    pixelDataAddress->G = buffer[row, column].G;
                    pixelDataAddress->B = buffer[row, column].B;
                }
            });
            temp.UnlockBits(bitmapData);
            return temp;
        }

19 View Source File : GitIndexProjection.LazyUTF8String.cs
License : MIT License
Project Creator : microsoft

public override unsafe void UnpinPool()
                {
                    if (this.poolHandle.IsAllocated)
                    {
                        this.poolHandle.Free();
                        this.RawPointer = (byte*)IntPtr.Zero.ToPointer();
                    }
                }

19 View Source File : GitIndexProjection.LazyUTF8String.cs
License : MIT License
Project Creator : microsoft

protected override unsafe void PinPool()
                {
                    this.poolHandle = GCHandle.Alloc(this.Pool, GCHandleType.Pinned);
                    this.RawPointer = (byte*)this.poolHandle.AddrOfPinnedObject().ToPointer();
                }

19 View Source File : Win32Native.cs
License : MIT License
Project Creator : microsoftarchive

[SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "Protected as a SecurityCritical method")]
        internal T Read<T>(int offset) where T : struct
        {
            bool addedRef = false;
            RuntimeHelpers.PrepareConstrainedRegions();
            try
            {
                DangerousAddRef(ref addedRef);

                unsafe
                {
                    IntPtr pBase = new IntPtr((byte*)handle.ToPointer() + offset);
                    return (T)Marshal.PtrToStructure(pBase, typeof(T));
                }
            }
            finally
            {
                if (addedRef)
                {
                    DangerousRelease();
                }
            }

        }

19 View Source File : Win32Native.cs
License : MIT License
Project Creator : microsoftarchive

[SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "Protected as a SecurityCritical method")]
        internal T[] ReadArray<T>(int offset, int count) where T : struct
        {
            Debug.replacedert(offset >= 0);
            Debug.replacedert(count >= 0);

            T[] array = new T[count];
            checked
            {
                // Figure out how big each structure is within the buffer.
                uint structSize = (uint)Marshal.SizeOf(typeof(T));
                if (structSize % UIntPtr.Size != 0)
                {
                    structSize += (uint)(UIntPtr.Size - (structSize % UIntPtr.Size));
                }

                bool addedRef = false;
                RuntimeHelpers.PrepareConstrainedRegions();
                try
                {
                    DangerousAddRef(ref addedRef);

                    for (int i = 0; i < count; ++i)
                    {
                        unsafe
                        {
                            UIntPtr pElement = new UIntPtr((byte*)handle.ToPointer() + offset + (structSize * i));
                            array[i] = (T)Marshal.PtrToStructure(new IntPtr(pElement.ToPointer()), typeof(T));
                        }
                    }
                }
                finally
                {
                    if (addedRef)
                    {
                        DangerousRelease();
                    }
                }
            }

            return array;
        }

19 View Source File : CapiNative.cs
License : MIT License
Project Creator : microsoftarchive

[SecurityCritical]
        internal static byte[] ReadBlob(CRYPTOAPI_BLOB capiBlob)
        {
            byte[] managedBlob = new byte[capiBlob.cbData];

            unsafe
            {
                byte* pCapiBlob = (byte*)capiBlob.pbData.ToPointer();
                for (int i = 0; i < managedBlob.Length; ++i)
                {
                    managedBlob[i] = pCapiBlob[i];
                }
            }

            return managedBlob;
        }

19 View Source File : NCryptNative.cs
License : MIT License
Project Creator : microsoftarchive

[SecurityCritical]
        [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "Safe use by a critical method")]
        internal T ReadArray<T>(uint index) where T : struct
        {
            checked
            {
                // Figure out how big each structure is within the buffer.
                uint structSize = (uint)Marshal.SizeOf(typeof(T));
                if (structSize % UIntPtr.Size != 0)
                {
                    structSize += (uint)(UIntPtr.Size - (structSize % UIntPtr.Size));
                }

                unsafe
                {
                    UIntPtr pBufferBase = new UIntPtr(handle.ToPointer());
                    UIntPtr pElement = new UIntPtr(pBufferBase.ToUInt64() + (structSize * index));
                    return (T)Marshal.PtrToStructure(new IntPtr(pElement.ToPointer()), typeof(T));
                }
            }
        }

19 View Source File : ImageUtil.cs
License : MIT License
Project Creator : migueldeicaza

public static unsafe TFTensor CreateTensorFromImageFileAlt(string inputFileName, TFDataType destinationDataType = TFDataType.Float)
                {
                  Bitmap bitmap = new Bitmap(inputFileName);

                  BitmapData data = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);

                  var matrix = new byte[1, bitmap.Height, bitmap.Width, 3];

                  byte* scan0 = (byte*)data.Scan0.ToPointer();
            
                  for (int i = 0; i < data.Height; i++)
                  {
                      for (int j = 0; j < data.Width; j++)
                      {
                          byte* pixelData = scan0 + i * data.Stride + j * 3;
                          matrix[0, i, j, 0] = pixelData[2];
                          matrix[0, i, j, 1] = pixelData[1];
                          matrix[0, i, j, 2] = pixelData[0];
                      }
                  }

                  bitmap.UnlockBits(data);

                  TFTensor tensor = matrix;

                  return tensor;
                }

19 View Source File : Mem.cs
License : MIT License
Project Creator : MiloszKrajewski

[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static void* Alloc(int size) =>
			Marshal.AllocHGlobal(size).ToPointer();

19 View Source File : TileSet.cs
License : GNU General Public License v3.0
Project Creator : minishmaker

public unsafe void SetPixel(int x, int y, Color c, ref BitmapData bd)
        {
            byte* pixels = (byte*)bd.Scan0.ToPointer();
            pixels[(x * 4) + (y * bd.Stride) + 0] = c.B; //B
            pixels[(x * 4) + (y * bd.Stride) + 1] = c.G; //G
            pixels[(x * 4) + (y * bd.Stride) + 2] = c.R; //R
            pixels[(x * 4) + (y * bd.Stride) + 3] = c.A; //A
        }

19 View Source File : ImageUtils.cs
License : GNU General Public License v3.0
Project Creator : misterokaygo

public static (Bitmap, Point) CropBitmap(Bitmap originalBitmap)
        {
            // Find the min/max non-white/transparent pixels
            var min = new Point(int.MaxValue, int.MaxValue);
            var max = new Point(int.MinValue, int.MinValue);

            unsafe
            {
                var bData = originalBitmap.LockBits(new Rectangle(0, 0, originalBitmap.Width, originalBitmap.Height), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);
                byte bitsPerPixel = 32;
                var scan0 = (byte*)bData.Scan0.ToPointer();

                for (var y = 0; y < bData.Height; ++y)
                {
                    for (var x = 0; x < bData.Width; ++x)
                    {
                        var data = scan0 + y * bData.Stride + x * bitsPerPixel / 8;
                        // data[0 = blue, 1 = green, 2 = red, 3 = alpha]
                        if (data[3] == byte.MaxValue)
                        {
                            if (x < min.X) min.X = x;
                            if (y < min.Y) min.Y = y;

                            if (x > max.X) max.X = x;
                            if (y > max.Y) max.Y = y;
                        }
                    }
                }
                originalBitmap.UnlockBits(bData);
            }

            // Create a new bitmap from the crop rectangle
            var cropRectangle = new Rectangle(min.X, min.Y, max.X - min.X, max.Y - min.Y);
            var newBitmap = new Bitmap(cropRectangle.Width, cropRectangle.Height);
            using (var g = Graphics.FromImage(newBitmap))
            {
                g.DrawImage(originalBitmap, 0, 0, cropRectangle, GraphicsUnit.Pixel);
            }

            return (newBitmap, min);
        }

19 View Source File : NativeENetBuffer.cs
License : MIT License
Project Creator : moien007

public unsafe Span<byte> replacedpan()
        {
            return new Span<byte>(Data.ToPointer(), unchecked((int)DataLength));
        }

19 View Source File : NativeENetPacket.cs
License : MIT License
Project Creator : moien007

public unsafe Span<byte> GetDatareplacedpan()
        {
            return new Span<byte>(Data.ToPointer(), unchecked((int)DataLength));
        }

19 View Source File : FastBitmap.cs
License : GNU General Public License v2.0
Project Creator : nesherhh

public void LockBits()
		{
			if (isLocked) return;
			try
			{
				bitmapData = bitmap.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadWrite, bitmap.PixelFormat);
				stride = bitmapData.Stride;
				pBase = (byte*) bitmapData.Scan0.ToPointer();
			}
			finally
			{
				isLocked = true;
			}
		}

19 View Source File : AdaptiveThreshold.cs
License : GNU General Public License v2.0
Project Creator : nesherhh

protected override unsafe void ProcessFilter(BitmapData imageData)
		{
			Destination = AForge.Imaging.Image.CreateGrayscaleImage(imageData.Width, imageData.Height);
			BitmapData dstData = Destination.LockBits(new Rectangle(0, 0, Destination.Width, Destination.Height), ImageLockMode.ReadWrite, Destination.PixelFormat);

			byte* srcPtr = (byte*)imageData.Scan0.ToPointer();
			byte* dstPtr = (byte*)dstData.Scan0.ToPointer();
			for (int y = 0; y < imageData.Height; y++)
			{
				for (int x = 0; x < imageData.Width; x++)
				{
					int mean = 0;
					int max = srcPtr[GetOffset(imageData.Stride, x, y)];
					int min = srcPtr[GetOffset(imageData.Stride, x, y)];


					for (int k = Size / 2; k < Size; k++)
					{
						for (int l = Size / 2; l < Size; l++)
						{
							byte pixel = srcPtr[GetOffset(imageData.Stride, x - Size / 2 + k, y - Size / 2 + l)];
							if (pixel > max)
								max = pixel;
							if (pixel < min)
								min = pixel;
						}
					}

					int tmp = max + min;
					tmp = tmp / 2;
					mean = tmp - Constant;
					if (srcPtr[GetOffset(imageData.Stride, x, y)] >= mean)
						dstPtr[GetOffset(dstData.Stride, x, y)] = 255;
					else
						dstPtr[GetOffset(dstData.Stride, x, y)] = 0;
				}
			}

			byte[] buffer = new byte[dstData.Width * dstData.Height];
			Marshal.Copy(dstData.Scan0, buffer, 0, buffer.Length);
			Marshal.Copy(buffer, 0, imageData.Scan0, buffer.Length);

			Destination.UnlockBits(dstData);
		}

See More Examples