System.Runtime.InteropServices.Marshal.SizeOf(T)

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

98 Examples 7

19 Source : StructHelper.cs
with MIT License
from albyho

public static byte[] StructToBytes<T>(T structObj) where T : struct
        {
            //得到结构体的大小
            Int32 size = Marshal.SizeOf(structObj);
            //创建byte数组
            var bytes = new byte[size];
            //分配结构体大小的内存空间
            IntPtr structPtr = Marshal.AllocHGlobal(size);
            //将结构体拷到分配好的内存空间
            Marshal.StructureToPtr(structObj, structPtr, false);
            //从内存空间拷到byte数组
            Marshal.Copy(structPtr, bytes, 0, size);
            //释放内存空间
            Marshal.FreeHGlobal(structPtr);
            //返回byte数组
            return bytes;
        }

19 Source : Ring0.cs
with MIT License
from AlexGyver

public static bool ReadMemory<T>(ulong address, ref T buffer) {
      if (driver == null) {
        return false;
      }

      ReadMemoryInput input = new ReadMemoryInput();
      input.address = address;
      input.unitSize = 1;
      input.count = (uint)Marshal.SizeOf(buffer);

      return driver.DeviceIOControl(IOCTL_OLS_READ_MEMORY, input,
        ref buffer);
    }

19 Source : Program.cs
with MIT License
from Analogy-LogViewer

private static IntPtr IntPtrAlloc<T>(T param)
        {
            IntPtr retval = Marshal.AllocHGlobal(Marshal.SizeOf(param));
            Marshal.StructureToPtr(param, retval, false);
            return retval;
        }

19 Source : Util.cs
with MIT License
from anastasios-stamoulis

public static int SizeOf<T>() where T : struct {
      // https://github.com/dotnet/roslyn/issues/3208#issuecomment-210134781
      return Marshal.SizeOf(default(T));
    }

19 Source : ExtensionMethods.cs
with GNU Lesser General Public License v2.1
from axiom3d

public static int CopyFrom<T>(this byte[] dst, T obj, int ofs)
        {
            var size = Marshal.SizeOf(obj);
            var handle = GCHandle.Alloc(obj, GCHandleType.Pinned);
            Marshal.Copy(handle.AddrOfPinnedObject(), dst, 0, size);
            handle.Free();
            return ofs + size;
        }

19 Source : ExtensionMethods.cs
with GNU Lesser General Public License v2.1
from axiom3d

public static int CopyTo<T>(this byte[] src, ref T obj, int ofs)
        {
            var size = Marshal.SizeOf(obj);
            var handle = GCHandle.Alloc(obj, GCHandleType.Pinned);
            Marshal.Copy(src, 0, handle.AddrOfPinnedObject(), size);
            handle.Free();
            return ofs + size;
        }

19 Source : StructConverter.cs
with GNU General Public License v3.0
from berichan

public static byte[] ToBytes<T>(this T obj) where T : struct
        {
            int size = Marshal.SizeOf(obj);
            byte[] arr = new byte[size];

            IntPtr ptr = Marshal.AllocHGlobal(size);
            Marshal.StructureToPtr(obj, ptr, true);
            Marshal.Copy(ptr, arr, 0, size);
            Marshal.FreeHGlobal(ptr);
            return arr;
        }

19 Source : StructConverter.cs
with GNU General Public License v3.0
from berichan

public static byte[] ToBytesClreplaced<T>(this T obj) where T : clreplaced
        {
            int size = Marshal.SizeOf(obj);
            byte[] arr = new byte[size];

            IntPtr ptr = Marshal.AllocHGlobal(size);
            Marshal.StructureToPtr(obj, ptr, true);
            Marshal.Copy(ptr, arr, 0, size);
            Marshal.FreeHGlobal(ptr);
            return arr;
        }

19 Source : Struct.cs
with GNU General Public License v3.0
from BorjaMerino

public static byte[] GetBytes<T>(T obj) where T : struct {
            byte[] data = new byte[Marshal.SizeOf(obj)];
            GCHandle handle = GCHandle.Alloc(data, GCHandleType.Pinned);

            try {
                Marshal.StructureToPtr(obj, handle.AddrOfPinnedObject(), false);
                return ConvertEndian<T>(data);
            } finally {
                handle.Free();
            }
        }

19 Source : ReadOnlyNetworkMessage.cs
with GNU General Public License v3.0
from caioavidal

private static int SizeOf<T>() where T : struct
        {
            return Marshal.SizeOf(default(T));
        }

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

public T[] GetBlobAsArrayOf<T>()
        {
            var blobByteLength = blobVal.Length;
            var singleInstance = (T) Activator.CreateInstance(typeof(T));
            var structSize = Marshal.SizeOf(singleInstance);
            if (blobByteLength % structSize != 0)
            {
                throw new InvalidDataException(String.Format("Blob size {0} not a multiple of struct size {1}",
                    blobByteLength, structSize));
            }
            var items = blobByteLength / structSize;
            var array = new T[items];
            for (int n = 0; n < items; n++)
            {
                array[n] = (T) Activator.CreateInstance(typeof(T));
                Marshal.PtrToStructure(new IntPtr((long) blobVal.Data + n * structSize), array[n]);
            }
            return array;
        }

19 Source : Socket.cs
with MIT License
from citronneur

public static void Send<T>(IntPtr socket, T payload) where T : struct
        {
            int size = Marshal.SizeOf(payload);
            IntPtr unmanagedPointer = Marshal.AllocHGlobal(size);
            Marshal.StructureToPtr(payload, unmanagedPointer, false);

            int sendLength = 0;

            while(sendLength < size)
            {
                int result = send(socket, unmanagedPointer + sendLength, size - sendLength, 0);
                if (result < 0)
                {
                    Marshal.FreeHGlobal(unmanagedPointer);
                    throw new Exception("Unable to send message " + WSAGetLastError());
                }
                sendLength += result;
            }
            Marshal.FreeHGlobal(unmanagedPointer);
        }

19 Source : SPApiWrapper.cs
with MIT License
from cm-pony

public int GetCaptureSessionParam<T>(ushort command, ref T value) {
            int size = Marshal.SizeOf(value);
            ShadowPlayApi.Args.GetCaptureSessionParams captureSessionParams = new ShadowPlayApi.Args.GetCaptureSessionParams
            {
                api_version = 0x10020,
                hSession = hSession == 0 ? uint.MaxValue : hSession,
                command = command,
                uiDataSize = Convert.ToUInt32(size),
                pvalue = Marshal.AllocCoTaskMem(size)
            };
            Marshal.StructureToPtr(value, captureSessionParams.pvalue, true);
            int result = api.GetCaptureSessionParam(hProxyInterface, ref captureSessionParams);
            if (result == 0)
            {
                value =  Marshal.PtrToStructure<T>(captureSessionParams.pvalue);
            }
            Marshal.FreeCoTaskMem(captureSessionParams.pvalue);
            return result;
        }

19 Source : Common.cs
with MIT License
from copyliu

public static IntPtr IntPtrFromStuctArray<T>(T[] InputArray) where T : new()
        {
            int size = InputArray.Length;
            T[] resArray = new T[size];
            //IntPtr[] InPointers = new IntPtr[size];
            int dim = IntPtr.Size * size;
            IntPtr rRoot = Marshal.AllocCoTaskMem(Marshal.SizeOf(InputArray[0]) * size);
            for (int i = 0; i < size; i++)
            {
                Marshal.StructureToPtr(InputArray[i], (IntPtr)(rRoot.ToInt32() +
                                                               i * Marshal.SizeOf(InputArray[i])), false);
            }
            return rRoot;
        }

19 Source : Common.cs
with MIT License
from copyliu

public static T[] StuctArrayFromIntPtr<T>(IntPtr outArray, int size) where T : new()
        {
            T[] resArray = new T[size];
            IntPtr current = outArray;
            for (int i = 0; i < size; i++)
            {
                resArray[i] = new T();
                resArray[i]=(T)Marshal.PtrToStructure(current, typeof(T));
                Marshal.DestroyStructure(current, typeof(T));
                int structsize = Marshal.SizeOf(resArray[i]);
                current = (IntPtr)((long)current + structsize);
            }
            Marshal.FreeCoTaskMem(outArray);
            return resArray;
        }

19 Source : Utility.cs
with BSD 3-Clause "New" or "Revised" License
from cube0x0

public static byte[] StructToBytes<T>(T str)
        {
            int size = Marshal.SizeOf(str);
            byte[] arr = new byte[size];

            IntPtr ptr = Marshal.AllocHGlobal(size);
            Marshal.StructureToPtr(str, ptr, true);
            Marshal.Copy(ptr, arr, 0, size);
            Marshal.FreeHGlobal(ptr);
            return arr;
        }

19 Source : DataExtensions.cs
with MIT License
from Cuyler36

public static T GetBit<T>(this T input, int index, bool reverse = false)
        {
            if (!(input is ValueType))
                throw new ArgumentException($"{nameof(input)} must be a ValueType!");

            var highBit = Marshal.SizeOf(input) * 8 - 1;
            if (index < 0 || index > highBit)
                throw new ArgumentException($"Bit index was out of range! Expected range: 0 - {highBit}");

            dynamic obj = input;
            return (T) ((reverse ? obj >> (highBit - index) : obj >> index) & 1);
        }

19 Source : DataExtensions.cs
with MIT License
from Cuyler36

public static T SetBit<T>(this T input, int index, bool set, bool reverse = false)
        {
            if (!(input is ValueType))
                throw new ArgumentException($"{nameof(input)} must be a ValueType!");

            var highBit = Marshal.SizeOf(input) * 8 - 1;
            if (index < 0 || index > highBit)
                throw new ArgumentException($"Bit index was out of range! Expected range: 0 - {highBit}");

            var bitmask = 1 << (reverse ? highBit - index : index);
            dynamic obj = input;

            if (set)
            {
                obj |= bitmask;
            }
            else
            {
                obj &= ~bitmask;
            }

            return (T) obj;
        }

19 Source : Extensions.cs
with GNU General Public License v3.0
from CypherCore

public static void WriteStruct<T>(this BinaryWriter writer, T obj) where T : struct
        {
            int length = Marshal.SizeOf(obj);
            IntPtr ptr = Marshal.AllocHGlobal(length);
            byte[] myBuffer = new byte[length];

            Marshal.StructureToPtr(obj, ptr, true);
            Marshal.Copy(ptr, myBuffer, 0, length);
            Marshal.FreeHGlobal(ptr);

            writer.Write(myBuffer);
        }

19 Source : Memory.cs
with MIT License
from DaanBanaan121

public void Write<T>(T input, IntPtr Address)
        {
            int size = Marshal.SizeOf(input);
            byte[] arr = new byte[size];

            IntPtr ptr = Marshal.AllocHGlobal(size);
            Marshal.StructureToPtr(input, ptr, true);
            Marshal.Copy(ptr, arr, 0, size);
            Marshal.FreeHGlobal(ptr);
            WriteMemory(arr, Address);
        }

19 Source : InteropUtil.cs
with MIT License
from dahall

public static IntPtr StructureToPtr<T>(this T value) where T : struct
		{
			var ret = Marshal.AllocHGlobal(Marshal.SizeOf(value));
			Marshal.StructureToPtr(value, ret, false);
			return ret;
		}

19 Source : IOExtensions.cs
with MIT License
from dahall

public static void Write<T>(this BinaryWriter writer, T value)
		{
			if (value == null) return;
			if (!typeof(T).IsBlittable())
				throw new ArgumentException(@"The type parameter layout is not sequential or explicit.", nameof(T));
			var sz = Marshal.SizeOf(value);
			var bytes = new byte[sz];
			using (var ptr = new PinnedObject(value))
				Marshal.Copy(ptr, bytes, 0, sz);
			writer.Write(bytes);
		}

19 Source : WinBase.Profile.cs
with MIT License
from dahall

public static bool WritePrivateProfileStruct<T>(string lpszSection, string lpszKey, in T lpStruct, string szFile) where T : unmanaged =>
			WritePrivateProfileStruct(lpszSection, lpszKey, new PinnedObject(lpStruct), (uint)Marshal.SizeOf(lpStruct), szFile);

19 Source : ComputeTools.cs
with MIT License
from deepakkumar1984

internal static int SizeOf<T>()
        {
            return typeof (T).IsGenericType ? Marshal.SizeOf(default(T)) : Marshal.SizeOf(typeof(T));
        }

19 Source : ComputeTools.cs
with MIT License
from deepakkumar1984

internal static int SizeOf<T>(T data)
        {
            return Marshal.SizeOf(data);
        }

19 Source : SDKBridge.cs
with MIT License
from DrBibop

public static void AddStructToFrame<T>(ref T mystruct, ulong tag)
        {
            GCHandle gch = GCHandle.Alloc(mystruct, GCHandleType.Pinned);
            AddObjectToFrame(gch.AddrOfPinnedObject(), Marshal.SizeOf(mystruct), tag);
            gch.Free();
        }

19 Source : SDKBridge.cs
with MIT License
from DrBibop

public static int AddStructToGlobalChannel<T>(ref T mystruct, int channel, ulong tag)
        {
            GCHandle gch = GCHandle.Alloc(mystruct, GCHandleType.Pinned);
            int output = AddObjectToCompositorChannel(channel, gch.AddrOfPinnedObject(), Marshal.SizeOf(mystruct), tag);
            gch.Free();
            return output;
        }

19 Source : SDKBridge.cs
with MIT License
from DrBibop

public static int AddStructToLocalChannel<T>(ref T mystruct, int channel, ulong tag)
        {
            GCHandle gch = GCHandle.Alloc(mystruct, GCHandleType.Pinned);
            int output = AddObjectToChannel(channel, gch.AddrOfPinnedObject(), Marshal.SizeOf(mystruct), tag);
            gch.Free();
            return output;
        }

19 Source : StructExtensions.cs
with MIT License
from fbarresi

public static byte[] GetBytes<T>(this T obj) where T : struct
    {
      int length = Marshal.SizeOf<T>(obj);
      IntPtr num = Marshal.AllocHGlobal(length);
      try
      {
        byte[] destination = new byte[length];
        Marshal.StructureToPtr<T>(obj, num, true);
        Marshal.Copy(num, destination, 0, length);
        return destination;
      }
      finally
      {
        Marshal.FreeHGlobal(num);
      }
    }

19 Source : StructExtensions.cs
with MIT License
from fbarresi

public static int GetSize<T>(this T obj) where T : struct => Marshal.SizeOf<T>(obj);

19 Source : Counter.cs
with MIT License
from Fobri

public static unsafe void CopyToFast<T>(this NativeSlice<T> source, T[] target) where T : struct
        {
            if (target == null)
            {
                throw new NullReferenceException(nameof(target) + " is null");
            }

            int nativeArrayLength = source.Length;
            if (target.Length < nativeArrayLength)
            {
                throw new IndexOutOfRangeException(nameof(target) + " is shorter than " + nameof(source));
            }

            int byteLength = source.Length * Marshal.SizeOf(default(T));
            void* managedBuffer = UnsafeUtility.AddressOf(ref target[0]);
            void* nativeBuffer = source.GetUnsafePtr();
            Buffer.MemoryCopy(nativeBuffer, managedBuffer, byteLength, byteLength);
        }

19 Source : OSHelper.cs
with MIT License
from funwaywang

public static IntPtr IntPtrAlloc<T>(T param)
        {
            IntPtr retval = Marshal.AllocHGlobal(Marshal.SizeOf(param));
            Marshal.StructureToPtr(param, retval, false);
            return (retval);
        }

19 Source : Utils.cs
with GNU General Public License v3.0
from furesoft

public static T FromBytes<T>(byte[] arr)
            where T : struct
        {
            T str = new T();

            int size = Marshal.SizeOf(str);
            var ptr = Marshal.AllocHGlobal(size);

            Marshal.Copy(arr, 0, ptr, size);

            str = (T)Marshal.PtrToStructure(ptr, str.GetType());
            Marshal.FreeHGlobal(ptr);

            return str;
        }

19 Source : Utils.cs
with GNU General Public License v3.0
from furesoft

public static byte[] GetBytes<T>(T str)
            where T : struct
        {
            int size = Marshal.SizeOf(str);
            byte[] arr = new byte[size];

            var ptr = Marshal.AllocHGlobal(size);
            Marshal.StructureToPtr(str, ptr, true);
            Marshal.Copy(ptr, arr, 0, size);
            Marshal.FreeHGlobal(ptr);
            return arr;
        }

19 Source : StructExtensions.cs
with MIT License
from Fusion86

public static byte[] ToBytes<T>(this T data)
        {
            byte[] bytes = new byte[Marshal.SizeOf(data)];
            GCHandle handle = GCHandle.Alloc(bytes, GCHandleType.Pinned);

            try
            {
                IntPtr rawDataPtr = handle.AddrOfPinnedObject();
                Marshal.StructureToPtr(data, rawDataPtr, false);
            }
            finally
            {
                handle.Free();
            }

            EndiannessHelper.RespectEndianness(typeof(T), bytes);

            return bytes;
        }

19 Source : Kernel.cs
with MIT License
from Haato3o

public static bool Write<T>(long address, T data) where T : struct
        {
            int dataSize = Marshal.SizeOf(data);

            byte[] buffer = new byte[dataSize];

            IntPtr unmanagedPtr = Marshal.AllocHGlobal(dataSize);
            Marshal.StructureToPtr(data, unmanagedPtr, true);
            Marshal.Copy(unmanagedPtr, buffer, 0, dataSize);

            Marshal.FreeHGlobal(unmanagedPtr);
            return WriteProcessMemory(ProcessHandle, (IntPtr)address, buffer, buffer.Length, out _);
        }

19 Source : StructHelper.cs
with GNU General Public License v3.0
from Hyddwn

public static byte[] GetBytes<T>(this T obj) where T : struct
		{
			var size = Marshal.SizeOf(obj);
			var arr = new byte[size];
			var ptr = Marshal.AllocHGlobal(size);

			Marshal.StructureToPtr(obj, ptr, true);
			Marshal.Copy(ptr, arr, 0, size);
			Marshal.FreeHGlobal(ptr);

			return arr;
		}

19 Source : WrapperTest.cs
with MIT License
from hzexe

private void sizeTest<T>(T cls) where T : new()
        {
            replacedert.True(Marshal.SizeOf(cls) > 0);
        }

19 Source : OSCUtilities.cs
with MIT License
from Iam1337

private static int StructSizeOf<T>(T structure) where T : struct
		{
#if !UNITY_WSA
			return Marshal.SizeOf(structure);
#else
            return Marshal.SizeOf<T>(structure);
#endif
		}

19 Source : PInvoke.cs
with GNU General Public License v3.0
from indiff

public static IntPtr SendMessage<T>(IntPtr hWnd, uint Msg, IntPtr wParam, ref T lParam) {
            IntPtr ptr = Marshal.AllocHGlobal(Marshal.SizeOf(lParam));
            try {
                Marshal.StructureToPtr(lParam, ptr, false);
                IntPtr ret = SendMessage(hWnd, Msg, wParam, ptr);
                lParam = (T)Marshal.PtrToStructure(ptr, typeof(T));
                return ret;
            }
            finally {
                if(ptr != IntPtr.Zero) Marshal.FreeHGlobal(ptr);
            }
        }

19 Source : Structs.cs
with MIT License
from inthehand

internal static void replacedertSize<T>(ref T stru, int expectedSize)
                  where T : struct
            {
                int actual = Marshal.SizeOf(stru);
                if (actual != expectedSize)
                    throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture,
                        "Wrong STRUCT size {0}, expected {1} but was {2}.",
                       stru.GetType().Name, expectedSize, actual));
            }

19 Source : WzSoundProperty.cs
with GNU General Public License v3.0
from izarooni

private static byte[] StructToBytes<T>(T obj)
        {
            byte[] result = new byte[Marshal.SizeOf(obj)];
            GCHandle handle = GCHandle.Alloc(result, GCHandleType.Pinned);
            try
            {
                Marshal.StructureToPtr(obj, handle.AddrOfPinnedObject(), false);
                return result;
            }
            finally
            {
                handle.Free();
            }
        }

19 Source : Program.cs
with The Unlicense
from jeremyVignelles

public static void UseStructurePointer<T>(T structure, Action<IntPtr> action)
        {
            var listPointer = Marshal.AllocHGlobal(Marshal.SizeOf(structure));
            try
            {
                Marshal.StructureToPtr(structure, listPointer, false);
                action(listPointer);
            }
            finally
            {
                Marshal.FreeHGlobal(listPointer);
            }
        }

19 Source : Protocol.cs
with MIT License
from justarandomgeek

public static byte[] getBytes<T>(T str)
        {
            int size = Marshal.SizeOf(str);
            byte[] arr = new byte[size];
            IntPtr ptr = Marshal.AllocHGlobal(size);

            Marshal.StructureToPtr(str, ptr, true);
            Marshal.Copy(ptr, arr, 0, size);
            Marshal.FreeHGlobal(ptr);

            return arr;
        }

19 Source : Protocol.cs
with MIT License
from justarandomgeek

public static T fromBytes<T>(byte[] arr, int startIndex = 0)
        {
            T str = default(T);

            int size = Marshal.SizeOf(str);
            IntPtr ptr = Marshal.AllocHGlobal(size);

            Marshal.Copy(arr, startIndex, ptr, size);

            str = (T)Marshal.PtrToStructure(ptr, str.GetType());
            Marshal.FreeHGlobal(ptr);

            return str;
        }

19 Source : Memory.cs
with MIT License
from kagurazakasanae

public void Write<T>(T input, IntPtr Address)
        {
            int size = Marshal.SizeOf(input);
            byte[] arr = new byte[size];

            IntPtr ptr = Marshal.AllocHGlobal(size);
            Marshal.StructureToPtr(input, ptr, true);
            Marshal.Copy(ptr, arr, 0, size);
            Marshal.FreeHGlobal(ptr);
            Write(Address, arr);
        }

19 Source : NP.CNTKHelper.cs
with MIT License
from KIWI-ST

public static int SizeOf<T>() where T : struct
            {
                return Marshal.SizeOf(default(T));
            }

19 Source : InteropUtil.cs
with BSD 3-Clause "New" or "Revised" License
from Krypton-Suite

public static IntPtr StructureToPtr<T>(this T value) where T : struct
        {
            var ret = Marshal.AllocHGlobal(Marshal.SizeOf(value));
            Marshal.StructureToPtr(value, ret, false);
            return ret;
        }

19 Source : StructUtil.cs
with GNU General Public License v2.0
from kwsch

public static byte[] ToBytesClreplaced<T>(this T obj) where T : clreplaced
        {
            var size = Marshal.SizeOf(obj);
            var arr = new byte[size];
            var ptr = Marshal.AllocHGlobal(size);

            Marshal.StructureToPtr(obj, ptr, true);
            Marshal.Copy(ptr, arr, 0, size);
            Marshal.FreeHGlobal(ptr);
            return arr;
        }

19 Source : CUDA.cs
with GNU Lesser General Public License v2.1
from lepoco

public void SetParameter<T>(CUfunction func, int offset, T vector)
        {
            GCHandle handle = GCHandle.Alloc(vector, GCHandleType.Pinned);
            int size = Marshal.SizeOf(vector);
            this.LastError = CUDADriver.cuParamSetv(func, offset, handle.AddrOfPinnedObject(), (uint)size );
            handle.Free();
        }

See More Examples