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

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

83 Examples 7

19 Source : KernelDriver.cs
with MIT License
from AlexGyver

public bool DeviceIOControl(IOControlCode ioControlCode, object inBuffer) {
      if (device == null)
        return false;

      uint bytesReturned;
      bool b = NativeMethods.DeviceIoControl(device, ioControlCode,
        inBuffer, inBuffer == null ? 0 : (uint)Marshal.SizeOf(inBuffer),
        null, 0, out bytesReturned, IntPtr.Zero);
      return b;
    }

19 Source : KernelDriver.cs
with MIT License
from AlexGyver

public bool DeviceIOControl<T>(IOControlCode ioControlCode, object inBuffer, 
      ref T outBuffer) 
    {
      if (device == null)
        return false;

      object boxedOutBuffer = outBuffer;
      uint bytesReturned;
      bool b = NativeMethods.DeviceIoControl(device, ioControlCode,
        inBuffer, inBuffer == null ? 0 : (uint)Marshal.SizeOf(inBuffer),
        boxedOutBuffer, (uint)Marshal.SizeOf(boxedOutBuffer),
        out bytesReturned, IntPtr.Zero);
      outBuffer = (T)boxedOutBuffer;
      return b;
    }

19 Source : OverlayBase`1.cs
with GNU General Public License v2.0
from AmanoTooko

public void Init()
            {
                this.biSize = (uint)Marshal.SizeOf((object)this);
            }

19 Source : XdeGuestLocator.cs
with MIT License
from anderm

private static byte[] GetStructureBytes(object obj)
        {
            var bytes = new byte[Marshal.SizeOf(obj)];

            var handle = GCHandle.Alloc(bytes, GCHandleType.Pinned);
            Marshal.StructureToPtr(obj, handle.AddrOfPinnedObject(), false);
            handle.Free();

            return bytes;
        }

19 Source : UnityDebugViewerTransferUtility.cs
with Apache License 2.0
from AsanCai

public static byte[] StructToBytes(object data)
        {
            /// 得到结构体的大小
            int size = Marshal.SizeOf(data);
            /// 分配结构体大小的空间
            IntPtr structPtr = Marshal.AllocHGlobal(size);
            /// 将结构体存储到分配好的空间
            Marshal.StructureToPtr(data, structPtr, false);

            byte[] bytes = new byte[size];

            /// 从内存空间拷贝到byte数组
            Marshal.Copy(structPtr, bytes, 0, size);
            /// 释放内存空间
            Marshal.FreeHGlobal(structPtr);

            return bytes;
        }

19 Source : StackSizeValidator.cs
with MIT License
from ashmind

private static int EstimateSizeOfPush(Instruction instruction, MethodDefinition method) {
            TypeReference GetParameterType(MethodDefinition m, int index) {
                if (!m.IsStatic) {
                    if (index == 0)
                        return m.DeclaringType;
                    index -= 1;
                }
                return m.Parameters[index].ParameterType;
            }
            int GetSize(TypeReference t) => TypeSizeCalculator.GetSize(t);

            switch (instruction.OpCode.Code) {
                case Code.Ldarg_0: return GetSize(GetParameterType(method, 0));
                case Code.Ldarg_1: return GetSize(GetParameterType(method, 1));
                case Code.Ldarg_2: return GetSize(GetParameterType(method, 2));
                case Code.Ldarg_3: return GetSize(GetParameterType(method, 3));
                case Code.Ldloc_0: return GetSize(method.Body.Variables[0].VariableType);
                case Code.Ldloc_1: return GetSize(method.Body.Variables[1].VariableType);
                case Code.Ldloc_2: return GetSize(method.Body.Variables[2].VariableType);
                case Code.Ldloc_3: return GetSize(method.Body.Variables[3].VariableType);
            }

            switch (instruction.Operand) {
                case FieldReference f: return GetSize(f.FieldType);
                case MethodReference m: return GetSize(m.ReturnType);
                case VariableDefinition v: return GetSize(v.VariableType);
                case ParameterDefinition p: return GetSize(p.ParameterType);
                case object o when o != null && o.GetType().IsPrimitive: return Marshal.SizeOf(o);
                default: return sizeof(long); // estimate
            }
        }

19 Source : VideoAPI.cs
with MIT License
from BoonyaCSharp-ASP

public static int SizeOf(object structure)
        {
            return Marshal.SizeOf(structure);
        }

19 Source : PS4DBG.cs
with MIT License
from ChendoChap

private static byte[] GetBytesFromObject(object obj)
        {
            int size = Marshal.SizeOf(obj);

            byte[] bytes = new byte[size];
            IntPtr ptr = Marshal.AllocHGlobal(size);

            Marshal.StructureToPtr(obj, ptr, false);
            Marshal.Copy(ptr, bytes, 0, size);

            Marshal.FreeHGlobal(ptr);

            return bytes;
        }

19 Source : ByteWriter.cs
with MIT License
from ChevyRay

public void WriteStructRaw(object obj)
        {
            int size = Marshal.SizeOf(obj);
            if (size > bufferSize)
            {
                if (bufferSize > 0)
                    Marshal.FreeHGlobal(buffer);
                buffer = Marshal.AllocHGlobal(size);
                bufferSize = size;
            }
            Marshal.StructureToPtr(obj, buffer, false);
            Reserve(size);
            Marshal.Copy(buffer, bytes, Count, size);
            Count += size;
        }

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

public virtual ErrorCode Read(object buffer, int timeout, out int transferLength) { return Transfer(buffer, 0, Marshal.SizeOf(buffer), timeout, out transferLength); }

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

public virtual ErrorCode Write(object buffer, int timeout, out int transferLength) { return Write(buffer, 0, Marshal.SizeOf(buffer), timeout, out transferLength); }

19 Source : InteropUtil.cs
with MIT License
from dahall

public static IntPtr StructureToPtr(object value)
		{
			IntPtr ret = Marshal.AllocHGlobal(Marshal.SizeOf(value));
			Marshal.StructureToPtr(value, ret, false);
			return ret;
		}

19 Source : OpenCLCompiler.cs
with MIT License
from deepakkumar1984

private Dictionary<int, GenericArrayMemory> BuildKernelArguments(KernelFunction method, object[] inputs, ComputeKernel kernel, long length, int? returnInputVariable = null)
        {
            int i = 0;
            Dictionary<int, GenericArrayMemory> result = new Dictionary<int, GenericArrayMemory>();

            foreach (var item in inputs)
            {
                int size = 0;
                if(item.GetType().IsArray)
                {
                    var mode = method.Parameters.ElementAt(i).Value.IOMode;
                    var flag = ComputeMemoryFlags.ReadWrite;
                    if (mode == IOMode.Out)
                        flag |= ComputeMemoryFlags.AllocateHostPointer;
                    else
                        flag |= ComputeMemoryFlags.UseHostPointer;
                    GenericArrayMemory mem = new GenericArrayMemory(_context, flag, (Array)item);
                    kernel.SetMemoryArgument(i, mem);
                    result.Add(i, mem);
                }
                else if (item.GetType().Name == "XArray" || item.GetType().BaseType.Name == "XArray")
                {
                    var mode = method.Parameters.ElementAt(i).Value.IOMode;
                    var flag = ComputeMemoryFlags.ReadWrite;
                    if (mode == IOMode.Out)
                        flag |= ComputeMemoryFlags.AllocateHostPointer;
                    else
                        flag |= ComputeMemoryFlags.UseHostPointer;
                    GenericArrayMemory mem = new GenericArrayMemory(_context, flag, (XArray)item);
                    kernel.SetMemoryArgument(i, mem);
                    result.Add(i, mem);
                }
                else
                {
                    size = Marshal.SizeOf(item);
                    var datagch = GCHandle.Alloc(item, GCHandleType.Pinned);
                    kernel.SetArgument(i, new IntPtr(size), datagch.AddrOfPinnedObject());
                }

                i++;
            }

            return result;
        }

19 Source : OpenCLCompiler.cs
with MIT License
from deepakkumar1984

private Dictionary<int, GenericArrayMemory> BuildKernelArguments(object[] inputs, ComputeKernel kernel, long length, int? returnInputVariable = null)
        {
            int i = 0;
            Dictionary<int, GenericArrayMemory> result = new Dictionary<int, GenericArrayMemory>();

            foreach (var item in inputs)
            {
                int size = 0;
                if (item.GetType().IsArray)
                {
                    var flag = ComputeMemoryFlags.ReadWrite;
                    flag |= ComputeMemoryFlags.UseHostPointer;
                    GenericArrayMemory mem = new GenericArrayMemory(_context, flag, (Array)item);
                    kernel.SetMemoryArgument(i, mem);
                    result.Add(i, mem);
                }
                else if (item.GetType().Name == "XArray" || item.GetType().BaseType.Name == "XArray")
                {
                    var flag = ComputeMemoryFlags.ReadWrite;
                    flag |= ComputeMemoryFlags.UseHostPointer;
                    GenericArrayMemory mem = new GenericArrayMemory(_context, flag, (XArray)item);
                    kernel.SetMemoryArgument(i, mem);
                    result.Add(i, mem);
                }
                else
                {
                    size = Marshal.SizeOf(item);
                    var datagch = GCHandle.Alloc(item, GCHandleType.Pinned);
                    kernel.SetArgument(i, new IntPtr(size), datagch.AddrOfPinnedObject());
                }

                i++;
            }

            return result;
        }

19 Source : SerializationHelpers.cs
with MIT License
from demonixis

public static IntPtr StructureToIntPtr(object str, out int size)
        {
            size = Marshal.SizeOf(str);
            IntPtr ptr = Marshal.AllocHGlobal(size);
            Marshal.StructureToPtr(str, ptr, false);            
            return ptr;
        }

19 Source : SerializationHelpers.cs
with MIT License
from demonixis

public static byte[] StructureToByteArray(object str)
        {
            int size = Marshal.SizeOf(str);
            byte[] arr = new byte[size];

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

19 Source : NTCrypto.cs
with MIT License
from Dionach

private static byte[] StructureToByteArray(object obj)
        {
            int len = Marshal.SizeOf(obj);

            byte[] arr = new byte[len];

            IntPtr ptr = Marshal.AllocHGlobal(len);

            Marshal.StructureToPtr(obj, ptr, true);

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

            Marshal.FreeHGlobal(ptr);

            return arr;
        }

19 Source : NativeStructs.cs
with GNU General Public License v3.0
from DSorlov

public static NativeStructs.CRYPTUI_WIZ_DIGITAL_SIGN_INFO InitSignInfoStruct(string fileName, X509Certificate2 signingCert, string timeStampServerUrl, string hashAlgorithm, SigningOption option)
        {
            NativeStructs.CRYPTUI_WIZ_DIGITAL_SIGN_INFO wizDigitalSignInfo = new NativeStructs.CRYPTUI_WIZ_DIGITAL_SIGN_INFO();
            wizDigitalSignInfo.dwSize = (uint) Marshal.SizeOf((object) wizDigitalSignInfo);
            wizDigitalSignInfo.dwSubjectChoice = 1U;
            wizDigitalSignInfo.pwszFileName = fileName;
            wizDigitalSignInfo.dwSigningCertChoice = 1U;
            wizDigitalSignInfo.pSigningCertContext = signingCert.Handle;
            wizDigitalSignInfo.pwszTimestampURL = timeStampServerUrl;
            wizDigitalSignInfo.dwAdditionalCertChoice = NativeStructs.GetCertChoiceFromSigningOption(option);
            NativeStructs.CRYPTUI_WIZ_DIGITAL_SIGN_EXTENDED_INFO signExtendedInfo = NativeStructs.InitSignInfoExtendedStruct("", "", hashAlgorithm);
            IntPtr ptr = Marshal.AllocCoTaskMem(Marshal.SizeOf((object) signExtendedInfo));
            Marshal.StructureToPtr((object) signExtendedInfo, ptr, false);
            wizDigitalSignInfo.pSignExtInfo = ptr;
            return wizDigitalSignInfo;
        }

19 Source : NativeStructs.cs
with GNU General Public License v3.0
from DSorlov

public static NativeStructs.CRYPTUI_WIZ_DIGITAL_SIGN_EXTENDED_INFO InitSignInfoExtendedStruct(string description, string moreInfoUrl, string hashAlgorithm)
        {
            NativeStructs.CRYPTUI_WIZ_DIGITAL_SIGN_EXTENDED_INFO signExtendedInfo = new NativeStructs.CRYPTUI_WIZ_DIGITAL_SIGN_EXTENDED_INFO();
            signExtendedInfo.dwSize = (uint) Marshal.SizeOf((object) signExtendedInfo);
            signExtendedInfo.dwAttrFlagsNotUsed = 0U;
            signExtendedInfo.pwszDescription = description;
            signExtendedInfo.pwszMoreInfoLocation = moreInfoUrl;
            signExtendedInfo.pszHashAlg = (string) null;
            signExtendedInfo.pwszSigningCertDisplayStringNotUsed = IntPtr.Zero;
            signExtendedInfo.hAdditionalCertStoreNotUsed = IntPtr.Zero;
            signExtendedInfo.psAuthenticatedNotUsed = IntPtr.Zero;
            signExtendedInfo.psUnauthenticatedNotUsed = IntPtr.Zero;
            if (hashAlgorithm != null)
                signExtendedInfo.pszHashAlg = hashAlgorithm;
            return signExtendedInfo;
        }

19 Source : SignatureHelper.cs
with GNU General Public License v3.0
from DSorlov

private static Collection<string> GetCertEKU(X509Certificate2 cert)
        {
            Collection<string> collection = new Collection<string>();
            IntPtr handle = cert.Handle;
            int pcbUsage = 0;
            IntPtr pUsage = IntPtr.Zero;
            if (!CRYPT32.CertGetEnhancedKeyUsage(handle, 0U, pUsage, out pcbUsage))
                throw new Win32Exception(Marshal.GetLastWin32Error());
            if (pcbUsage > 0)
            {
                IntPtr num = Marshal.AllocHGlobal(pcbUsage);
                try
                {
                    if (!CRYPT32.CertGetEnhancedKeyUsage(handle, 0U, num, out pcbUsage))
                        throw new Win32Exception(Marshal.GetLastWin32Error());
                    NativeStructs.CERT_ENHKEY_USAGE certEnhkeyUsage = (NativeStructs.CERT_ENHKEY_USAGE)Marshal.PtrToStructure(num, typeof(NativeStructs.CERT_ENHKEY_USAGE));
                    IntPtr ptr = certEnhkeyUsage.rgpszUsageIdentifier;
                    for (int index = 0; (long)index < (long)certEnhkeyUsage.cUsageIdentifier; ++index)
                    {
                        string str = Marshal.PtrToStringAnsi(Marshal.ReadIntPtr(ptr, index * Marshal.SizeOf((object)ptr)));
                        collection.Add(str);
                    }
                }
                finally
                {
                    Marshal.FreeHGlobal(num);
                }
            }
            return collection;
        }

19 Source : SignatureHelper.cs
with GNU General Public License v3.0
from DSorlov

private static Signature SignFile(NativeStructs.SigningOption option, string fileName, X509Certificate2 certificate, string timeStampServerUrl, string hashAlgorithm)
        {
            System.Management.Automation.Signature signature = (System.Management.Automation.Signature)null;
            IntPtr num = IntPtr.Zero;
            uint error = 0U;
            string hashAlgorithm1 = (string)null;
            CheckArgForNullOrEmpty(fileName, "fileName");
            CheckArgForNull((object)certificate, "certificate");

            if (!string.IsNullOrEmpty(timeStampServerUrl) && (timeStampServerUrl.Length <= 7 || timeStampServerUrl.IndexOf("http://", StringComparison.OrdinalIgnoreCase) != 0))
                throw new ArgumentException("Time stamp server url required");

            if (!string.IsNullOrEmpty(hashAlgorithm))
            {
                IntPtr oidInfo = CRYPT32.CryptFindOIDInfo(2U, Marshal.StringToHGlobalUni(hashAlgorithm), 0U);
                if (oidInfo == IntPtr.Zero)
                    throw new ArgumentException("Invalid hash algorithm");

                hashAlgorithm1 = ((NativeStructs.CRYPT_OID_INFO)Marshal.PtrToStructure(oidInfo, typeof(NativeStructs.CRYPT_OID_INFO))).pszOID;
            }
            if (!CertIsGoodForSigning(certificate))
                throw new ArgumentException("Supplied certificate cannot be used to sign files.");
            
            CheckIfFileExists(fileName);
            try
            {
                string timeStampServerUrl1 = (string)null;
                if (!string.IsNullOrEmpty(timeStampServerUrl))
                    timeStampServerUrl1 = timeStampServerUrl;
                NativeStructs.CRYPTUI_WIZ_DIGITAL_SIGN_INFO wizDigitalSignInfo = NativeStructs.InitSignInfoStruct(fileName, certificate, timeStampServerUrl1, hashAlgorithm1, option);
                num = Marshal.AllocCoTaskMem(Marshal.SizeOf((object)wizDigitalSignInfo));
                Marshal.StructureToPtr((object)wizDigitalSignInfo, num, false);
                bool flag = CRYPTUI.CryptUIWizDigitalSign(1U, IntPtr.Zero, IntPtr.Zero, num, IntPtr.Zero);
                Marshal.DestroyStructure(wizDigitalSignInfo.pSignExtInfo, typeof(NativeStructs.CRYPTUI_WIZ_DIGITAL_SIGN_EXTENDED_INFO));
                Marshal.FreeCoTaskMem(wizDigitalSignInfo.pSignExtInfo);
                if (!flag)
                {
                    error = SignatureHelper.GetLastWin32Error();
                    switch (error)
                    {
                        case 2147500037U:
                        case 2147942401U:
                        case 2147954407U:
                            flag = true;
                            break;
                        case 2148073480U:
                            throw new ArgumentException("InvalidHashAlgorithm");
                        default:
                            throw new ArgumentException(string.Format("CryptUIWizDigitalSign: failed: {0:x}", new object[1]
                              {
                                (object) error
                              }));
                    }
                }
                signature = !flag ? SignatureProxy.GenerateSignature(fileName, error) : SignatureHelper.GetSignature(fileName);
            }
            finally
            {
                Marshal.DestroyStructure(num, typeof(NativeStructs.CRYPTUI_WIZ_DIGITAL_SIGN_INFO));
                Marshal.FreeCoTaskMem(num);
            }
            return signature;
        }

19 Source : SignatureHelper.cs
with GNU General Public License v3.0
from DSorlov

private static uint GetWinTrustData(string fileName, out NativeStructs.WINTRUST_DATA wtData)
        {
            uint num1 = 2147500037U;
            IntPtr num2 = IntPtr.Zero;
            IntPtr num3 = IntPtr.Zero;
            Guid guid = new Guid("00AAC56B-CD44-11d0-8CC2-00C04FC295EE");
            try
            {
                num2 = Marshal.AllocCoTaskMem(Marshal.SizeOf((object)guid));
                Marshal.StructureToPtr((object)guid, num2, false);
                //NativeStructs.WINTRUST_DATA wintrustData = fileContent != null ? WINTRUST.InitWintrustDataStructFromBlob(WINTRUST.InitWintrustBlobInfoStruct(fileName, fileContent)) : WINTRUST.InitWintrustDataStructFromFile(WINTRUST.InitWintrustFileInfoStruct(fileName));
                NativeStructs.WINTRUST_DATA wintrustData = WINTRUST.InitWintrustDataStructFromFile(WINTRUST.InitWintrustFileInfoStruct(fileName));
                num3 = Marshal.AllocCoTaskMem(Marshal.SizeOf((object)wintrustData));
                Marshal.StructureToPtr((object)wintrustData, num3, false);
                num1 = WINTRUST.WinVerifyTrust(new IntPtr(-1), num2, num3);
                wtData = (NativeStructs.WINTRUST_DATA)Marshal.PtrToStructure(num3, typeof(NativeStructs.WINTRUST_DATA));
            }
            finally
            {
                Marshal.DestroyStructure(num2, typeof(Guid));
                Marshal.FreeCoTaskMem(num2);
                Marshal.DestroyStructure(num3, typeof(NativeStructs.WINTRUST_DATA));
                Marshal.FreeCoTaskMem(num3);
            }
            return num1;
        }

19 Source : WINTRUST.cs
with GNU General Public License v3.0
from DSorlov

public static NativeStructs.WINTRUST_DATA InitWintrustDataStructFromBlob(NativeStructs.WINTRUST_BLOB_INFO wbi)
        {
            NativeStructs.WINTRUST_DATA wintrustData = new NativeStructs.WINTRUST_DATA();
            wintrustData.cbStruct = (uint)Marshal.SizeOf((object)wbi);
            wintrustData.pPolicyCallbackData = IntPtr.Zero;
            wintrustData.pSIPClientData = IntPtr.Zero;
            wintrustData.dwUIChoice = 2U;
            wintrustData.fdwRevocationChecks = 0U;
            wintrustData.dwUnionChoice = 3U;
            IntPtr ptr = Marshal.AllocCoTaskMem(Marshal.SizeOf((object)wbi));
            Marshal.StructureToPtr((object)wbi, ptr, false);
            wintrustData.Choice.pBlob = ptr;
            wintrustData.dwStateAction = 1U;
            wintrustData.hWVTStateData = IntPtr.Zero;
            wintrustData.pwszURLReference = (string)null;
            wintrustData.dwProvFlags = 0U;
            return wintrustData;
        }

19 Source : WINTRUST.cs
with GNU General Public License v3.0
from DSorlov

public static NativeStructs.WINTRUST_DATA InitWintrustDataStructFromFile(NativeStructs.WINTRUST_FILE_INFO wfi)
        {
            NativeStructs.WINTRUST_DATA wintrustData = new NativeStructs.WINTRUST_DATA();
            wintrustData.cbStruct = (uint)Marshal.SizeOf((object)wintrustData);
            wintrustData.pPolicyCallbackData = IntPtr.Zero;
            wintrustData.pSIPClientData = IntPtr.Zero;
            wintrustData.dwUIChoice = 2U;
            wintrustData.fdwRevocationChecks = 0U;
            wintrustData.dwUnionChoice = 1U;
            IntPtr ptr = Marshal.AllocCoTaskMem(Marshal.SizeOf((object)wfi));
            Marshal.StructureToPtr((object)wfi, ptr, false);
            wintrustData.Choice.pFile = ptr;
            wintrustData.dwStateAction = 1U;
            wintrustData.hWVTStateData = IntPtr.Zero;
            wintrustData.pwszURLReference = (string)null;
            wintrustData.dwProvFlags = 0U;
            return wintrustData;
        }

19 Source : WINTRUST.cs
with GNU General Public License v3.0
from DSorlov

public static NativeStructs.WINTRUST_FILE_INFO InitWintrustFileInfoStruct(string fileName)
        {
            NativeStructs.WINTRUST_FILE_INFO wintrustFileInfo = new NativeStructs.WINTRUST_FILE_INFO();
            wintrustFileInfo.cbStruct = (uint)Marshal.SizeOf((object)wintrustFileInfo);
            wintrustFileInfo.pcwszFilePath = fileName;
            wintrustFileInfo.hFileNotUsed = IntPtr.Zero;
            wintrustFileInfo.pgKnownSubjectNotUsed = IntPtr.Zero;
            return wintrustFileInfo;
        }

19 Source : WINTRUST.cs
with GNU General Public License v3.0
from DSorlov

public static NativeStructs.WINTRUST_BLOB_INFO InitWintrustBlobInfoStruct(string fileName, string content)
        {
            NativeStructs.WINTRUST_BLOB_INFO wintrustBlobInfo = new NativeStructs.WINTRUST_BLOB_INFO();
            byte[] bytes = Encoding.Unicode.GetBytes(content);
            wintrustBlobInfo.gSubject.Data1 = 1614531615U;
            wintrustBlobInfo.gSubject.Data2 = (ushort)19289;
            wintrustBlobInfo.gSubject.Data3 = (ushort)19976;
            wintrustBlobInfo.gSubject.Data4 = new byte[8]
              {
                (byte) 183,
                (byte) 36,
                (byte) 210,
                (byte) 198,
                (byte) 41,
                (byte) 126,
                (byte) 243,
                (byte) 81
              };
            wintrustBlobInfo.cbStruct = (uint)Marshal.SizeOf((object)wintrustBlobInfo);
            wintrustBlobInfo.pcwszDisplayName = fileName;
            wintrustBlobInfo.cbMemObject = (uint)bytes.Length;
            wintrustBlobInfo.pbMemObject = Marshal.AllocCoTaskMem(bytes.Length);
            Marshal.Copy(bytes, 0, wintrustBlobInfo.pbMemObject, bytes.Length);
            return wintrustBlobInfo;
        }

19 Source : WINTRUST.cs
with GNU General Public License v3.0
from DSorlov

public static uint DestroyWintrustDataStruct(NativeStructs.WINTRUST_DATA wtd)
        {
            uint num1 = 2147500037U;
            IntPtr num2 = IntPtr.Zero;
            IntPtr num3 = IntPtr.Zero;
            Guid guid = new Guid("00AAC56B-CD44-11d0-8CC2-00C04FC295EE");
            try
            {
                num2 = Marshal.AllocCoTaskMem(Marshal.SizeOf((object)guid));
                Marshal.StructureToPtr((object)guid, num2, false);
                wtd.dwStateAction = 2U;
                num3 = Marshal.AllocCoTaskMem(Marshal.SizeOf((object)wtd));
                Marshal.StructureToPtr((object)wtd, num3, false);
                num1 = WINTRUST.WinVerifyTrust(IntPtr.Zero, num2, num3);
                wtd = (NativeStructs.WINTRUST_DATA)Marshal.PtrToStructure(num3, typeof(NativeStructs.WINTRUST_DATA));
            }
            finally
            {
                Marshal.DestroyStructure(num3, typeof(NativeStructs.WINTRUST_DATA));
                Marshal.FreeCoTaskMem(num3);
                Marshal.DestroyStructure(num2, typeof(Guid));
                Marshal.FreeCoTaskMem(num2);
            }
            if ((int)wtd.dwUnionChoice == 3)
            {
                Marshal.FreeCoTaskMem(((NativeStructs.WINTRUST_BLOB_INFO)Marshal.PtrToStructure(wtd.Choice.pBlob, typeof(NativeStructs.WINTRUST_BLOB_INFO))).pbMemObject);
                Marshal.DestroyStructure(wtd.Choice.pBlob, typeof(NativeStructs.WINTRUST_BLOB_INFO));
                Marshal.FreeCoTaskMem(wtd.Choice.pBlob);
            }
            else
            {
                Marshal.DestroyStructure(wtd.Choice.pFile, typeof(NativeStructs.WINTRUST_FILE_INFO));
                Marshal.FreeCoTaskMem(wtd.Choice.pFile);
            }
            return num1;
        }

19 Source : SizeCache.cs
with GNU General Public License v3.0
from easly1989

private static int GetSizeOf(Type t)
        {
            try
            {
                // Try letting the marshaler handle getting the size.
                // It can *sometimes* do it correctly
                // If it can't, fall back to our own methods.
                var o = Activator.CreateInstance(t);
                return Marshal.SizeOf(o);
            }
            catch (Exception)
            {
                int totalSize = 0;
                var fields = t.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);

                foreach (var field in fields)
                {
                    var attr = field.GetCustomAttributes(typeof(FixedBufferAttribute), false);

                    if (attr.Length > 0)
                    {
                        var fba = (FixedBufferAttribute)attr[0];
                        totalSize += GetSizeOf(fba.ElementType) * fba.Length;
                        continue;
                    }

                    totalSize += GetSizeOf(field.FieldType);
                }
                return totalSize;
            }
        }

19 Source : NativeHelper.cs
with GNU General Public License v3.0
from FanTranslatorsInternational

public static IntPtr MarshalObject(object obj)
        {
            var objSize = Marshal.SizeOf(obj);
            var ptr = Marshal.AllocHGlobal(objSize);
            Marshal.StructureToPtr(obj, ptr, true);

            return ptr;
        }

19 Source : Memory.cs
with MIT License
from floh22

private static byte[] StructureToByteArray(object obj)
        {
            int len = Marshal.SizeOf(obj);

            byte[] arr = new byte[len];

            IntPtr ptr = Marshal.AllocHGlobal(len);

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

            return arr;
        }

19 Source : GameProcess.cs
with MIT License
from Folleach

protected byte[] StructureToBytes(object value)
        {
            int size = Marshal.SizeOf(value);
            byte[] array = new byte[size];
            IntPtr ptr = Marshal.AllocHGlobal(size);
            Marshal.StructureToPtr(value, ptr, true);
            Marshal.Copy(ptr, array, 0, size);
            Marshal.FreeHGlobal(ptr);
            return array;
        }

19 Source : GameUtility.cs
with MIT License
from gmhevinci

public static byte[] StructToBytes(object structObject)
	{
		int structSize = Marshal.SizeOf(structObject);
		byte[] bytes = new byte[structSize];
		GCHandle bytesHandle = GCHandle.Alloc(bytes, GCHandleType.Pinned);
		IntPtr bytesPtr = bytesHandle.AddrOfPinnedObject();
		Marshal.StructureToPtr(structObject, bytesPtr, false);
		if (bytesHandle.IsAllocated)
			bytesHandle.Free();
		return bytes;
	}

19 Source : Marshal.cs
with MIT License
from GrapeCity

public static object[] GetObjectsForNativeVariants (IntPtr aSrcNativeVariant, int cVars)
		{
			if (cVars < 0)
				throw new ArgumentOutOfRangeException ("cVars", "cVars cannot be a negative number.");
			object[] objects = new object[cVars];
			for (int i = 0; i < cVars; i++)
				objects[i] = GetObjectForNativeVariant ((IntPtr)(aSrcNativeVariant.ToInt64 () +
					i * SizeOf (typeof(Variant))));
			return objects;
		}

19 Source : GeneralHelper.cs
with MIT License
from HoLLy-HaCKeR

public static byte[] SerializeObj(object obj)
        {
            int size = Marshal.SizeOf(obj);
            byte[] buffer = new byte[size];

            GCHandle handle = GCHandle.Alloc(buffer, GCHandleType.Pinned);
            IntPtr ptr = handle.AddrOfPinnedObject();
            Marshal.StructureToPtr(obj, ptr, false);
            handle.Free();
            return buffer;
        }

19 Source : TTSCore.cs
with MIT License
from iothua

Byte[] StructToBytes(Object structure)
        {
            Int32 size = Marshal.SizeOf(structure);
            IntPtr buffer = Marshal.AllocHGlobal(size);
            try
            {
                Marshal.StructureToPtr(structure,buffer,false);
                Byte[] bytes = new Byte[size];
                Marshal.Copy(buffer,bytes,0,size);
                return bytes;
            }
            finally
            {
                Marshal.FreeHGlobal(buffer);
            }
        }

19 Source : meshManager.cs
with MIT License
from IRCSS

void InitializeGPUBuffers()
    {

        
        int sizeOfVector3 = System.Runtime.InteropServices.Marshal.SizeOf((object)Vector3.zero);
        GPU_VertexBuffer = new ComputeBuffer(m_vertexBufferCPU.Length, sizeof(float)*8);
        GPU_VertexBuffer.SetData(m_vertexBufferCPU);

        GPU_defaultPositionsBuffer = new ComputeBuffer(m_verticesPosition.Length, sizeOfVector3);
        GPU_defaultPositionsBuffer.SetData(m_verticesPosition);
        

        int kernel = m_computeShader.FindKernel(kernelName);

        m_computeShader.SetBuffer(kernel, "_VertexBuffer",          GPU_VertexBuffer);
        m_computeShader.SetBuffer(kernel, "_InitialPositionBuffer", GPU_defaultPositionsBuffer);

        m_computeShader.SetFloat("_distanceBegin", ScaleFromWorldtoMeshSpace(m_colliderBeginDistance));
        m_computeShader.SetFloat("_distnaceEnd"  , ScaleFromWorldtoMeshSpace(m_colliderEndDistance  ));
        m_computeShader.SetFloat("_pushforce"    , m_pushforce                                       );
        m_computeShader.SetFloat("_elacticity"   , m_elasticity                                      );
        m_computeShader.SetFloat("_drag"         , m_drag                                            );

        Debug.Log(string.Format("Initialized the GPU buffers with {0} vertices, for the compute shader", m_verticesPosition.Length));


        if(m_renderingMethod == RenderMethod.WithDrawProcedural)
        {
            GPU_IndexBuffer = new GraphicsBuffer(GraphicsBuffer.Target.Index, m_indexBuffer.Length, sizeof(int));
            GPU_IndexBuffer.SetData(m_indexBuffer);
        }

    }

19 Source : CustomBitmap.cs
with MIT License
from Keboo

private void ValidateArrayAndGetInfo(Array pixels,
                                             out int elementSize,
                                             out int sourceBufferSize,
                                             out Type elementType)
        {
            //
            // replacedure that a valid pixels Array was provided.
            //
            if (pixels == null)
            {
                throw new ArgumentNullException("pixels");
            }

            if (pixels.Rank == 1)
            {
                if (pixels.GetLength(0) <= 0)
                {
                    throw new ArgumentException("pixels");
                }
                else
                {
                    checked
                    {
                        object exemplar = pixels.GetValue(0);
                        elementSize = Marshal.SizeOf(exemplar);
                        sourceBufferSize = pixels.GetLength(0) * elementSize;
                        elementType = exemplar.GetType();
                    }
                }

            }
            else if (pixels.Rank == 2)
            {
                if (pixels.GetLength(0) <= 0 || pixels.GetLength(1) <= 0)
                {
                    throw new ArgumentException("pixels");
                }
                else
                {
                    checked
                    {
                        object exemplar = pixels.GetValue(0, 0);
                        elementSize = Marshal.SizeOf(exemplar);
                        sourceBufferSize = pixels.GetLength(0) * pixels.GetLength(1) * elementSize;
                        elementType = exemplar.GetType();
                    }
                }
            }
            else
            {
                throw new ArgumentException("pixels");
            }
        }

19 Source : Memory.cs
with GNU General Public License v3.0
from KleskBY

private static byte[] StructureToByteArray(object obj)
        {
            int length = Marshal.SizeOf(obj);

            byte[] array = new byte[length];

            IntPtr pointer = Marshal.AllocHGlobal(length);

            Marshal.StructureToPtr(obj, pointer, true);
            Marshal.Copy(pointer, array, 0, length);
            Marshal.FreeHGlobal(pointer);

            return array;
        }

19 Source : Memory.cs
with GNU General Public License v3.0
from krxdev-kaan

public static byte[] StructureToByteArray(object obj)
        {
            int len = Marshal.SizeOf(obj);

            byte[] arr = new byte[len];

            IntPtr ptr = Marshal.AllocHGlobal(len);

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

            return arr;
        }

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

internal static SpeechAudioFormatInfo ToSpeechAudioFormatInfo(IntPtr waveFormatPtr)
        {
            WaveFormatEx waveFormatEx = (WaveFormatEx)Marshal.PtrToStructure(waveFormatPtr, typeof(WaveFormatEx));
            byte[] array = new byte[waveFormatEx.cbSize];
            IntPtr ptr = new IntPtr(waveFormatPtr.ToInt64() + Marshal.SizeOf((object)waveFormatEx));
            for (int i = 0; i < waveFormatEx.cbSize; i++)
            {
                array[i] = Marshal.ReadByte(ptr, i);
            }
            return new SpeechAudioFormatInfo((EncodingFormat)waveFormatEx.wFormatTag, (int)waveFormatEx.nSamplesPerSec, (short)waveFormatEx.wBitsPerSample, (short)waveFormatEx.nChannels, (int)waveFormatEx.nAvgBytesPerSec, (short)waveFormatEx.nBlockAlign, array);
        }

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

internal static IntPtr ProsodyToPtr(Prosody prosody, Collection<IntPtr> memoryBlocks)
        {
            if (prosody == null)
            {
                return IntPtr.Zero;
            }
            ProsodyInterop prosodyInterop = default(ProsodyInterop);
            prosodyInterop._pitch = prosody.Pitch;
            prosodyInterop._range = prosody.Range;
            prosodyInterop._rate = prosody.Rate;
            prosodyInterop._duration = prosody.Duration;
            prosodyInterop._volume = prosody.Volume;
            ContourPoint[] contourPoints = prosody.GetContourPoints();
            if (contourPoints != null)
            {
                int num = Marshal.SizeOf((object)contourPoints[0]);
                prosodyInterop._contourPoints = Marshal.AllocCoTaskMem(contourPoints.Length * num);
                memoryBlocks.Add(prosodyInterop._contourPoints);
                for (uint num2 = 0u; num2 < contourPoints.Length; num2++)
                {
                    Marshal.StructureToPtr((object)contourPoints[num2], (IntPtr)((long)prosodyInterop._contourPoints + num * num2), false);
                }
            }
            else
            {
                prosodyInterop._contourPoints = IntPtr.Zero;
            }
            IntPtr intPtr = Marshal.AllocCoTaskMem(Marshal.SizeOf((object)prosodyInterop));
            memoryBlocks.Add(intPtr);
            Marshal.StructureToPtr((object)prosodyInterop, intPtr, false);
            return intPtr;
        }

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

internal static void WriteWaveHeader(Stream stream, WAVEFORMATEX waveEx, long position, int cData)
        {
            RIFFHDR rIFFHDR = new RIFFHDR(0);
            BLOCKHDR bLOCKHDR = new BLOCKHDR(0);
            DATAHDR dATAHDR = new DATAHDR(0);
            int num = Marshal.SizeOf((object)rIFFHDR);
            int num2 = Marshal.SizeOf((object)bLOCKHDR);
            int length = waveEx.Length;
            int num3 = Marshal.SizeOf((object)dATAHDR);
            int num4 = num + num2 + length + num3;
            using (MemoryStream memoryStream = new MemoryStream())
            {
                BinaryWriter binaryWriter = new BinaryWriter(memoryStream);
                try
                {
                    rIFFHDR._len = num4 + cData - 8;
                    binaryWriter.Write(rIFFHDR._id);
                    binaryWriter.Write(rIFFHDR._len);
                    binaryWriter.Write(rIFFHDR._type);
                    bLOCKHDR._len = length;
                    binaryWriter.Write(bLOCKHDR._id);
                    binaryWriter.Write(bLOCKHDR._len);
                    binaryWriter.Write(waveEx.ToBytes());
                    dATAHDR._len = cData;
                    binaryWriter.Write(dATAHDR._id);
                    binaryWriter.Write(dATAHDR._len);
                    stream.Seek(position, SeekOrigin.Begin);
                    stream.Write(memoryStream.GetBuffer(), 0, (int)memoryStream.Length);
                }
                finally
                {
                    ((IDisposable)binaryWriter).Dispose();
                }
            }
        }

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

internal static MMSYSERR GetDeviceName(int deviceId, [MarshalAs(UnmanagedType.LPWStr)] out string prodName)
        {
            prodName = string.Empty;
            SafeNativeMethods.WAVEOUTCAPS caps = default(SafeNativeMethods.WAVEOUTCAPS);
            MMSYSERR mMSYSERR = SafeNativeMethods.waveOutGetDevCaps((IntPtr)deviceId, ref caps, Marshal.SizeOf((object)caps));
            if (mMSYSERR != 0)
            {
                return mMSYSERR;
            }
            prodName = caps.szPname;
            return MMSYSERR.NOERROR;
        }

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

internal void FragmentStateToPtr(FragmentState state, Collection<IntPtr> memoryBlocks)
        {
            _action = state.Action;
            _langId = state.LangId;
            _emphasis = state.Emphasis;
            _duration = state.Duration;
            if (state.SayAs != null)
            {
                _sayAs = Marshal.AllocCoTaskMem(Marshal.SizeOf((object)state.SayAs));
                memoryBlocks.Add(_sayAs);
                Marshal.StructureToPtr((object)state.SayAs, _sayAs, false);
            }
            else
            {
                _sayAs = IntPtr.Zero;
            }
            if (state.Phoneme != null)
            {
                short[] array = new short[state.Phoneme.Length + 1];
                for (uint num = 0u; num < state.Phoneme.Length; num++)
                {
                    array[num] = (short)state.Phoneme[num];
                }
                array[state.Phoneme.Length] = 0;
                int num2 = Marshal.SizeOf((object)array[0]);
                _phoneme = Marshal.AllocCoTaskMem(num2 * array.Length);
                memoryBlocks.Add(_phoneme);
                for (uint num3 = 0u; num3 < array.Length; num3++)
                {
                    Marshal.Copy(array, 0, _phoneme, array.Length);
                }
            }
            else
            {
                _phoneme = IntPtr.Zero;
            }
            _prosody = ProsodyInterop.ProsodyToPtr(state.Prosody, memoryBlocks);
        }

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

internal static IntPtr FragmentToPtr(List<TextFragment> textFragments, Collection<IntPtr> memoryBlocks)
		{
			TextFragmentInterop textFragmentInterop = default(TextFragmentInterop);
			int count = textFragments.Count;
			int num = Marshal.SizeOf((object)textFragmentInterop);
			IntPtr intPtr = Marshal.AllocCoTaskMem(num * count);
			memoryBlocks.Add(intPtr);
			for (int i = 0; i < count; i++)
			{
				textFragmentInterop._state.FragmentStateToPtr(textFragments[i].State, memoryBlocks);
				textFragmentInterop._textToSpeak = textFragments[i].TextToSpeak;
				textFragmentInterop._textOffset = textFragments[i].TextOffset;
				textFragmentInterop._textLength = textFragments[i].TextLength;
				Marshal.StructureToPtr((object)textFragmentInterop, (IntPtr)((long)intPtr + i * num), false);
			}
			return intPtr;
		}

19 Source : Utils.cs
with GNU General Public License v2.0
from lfz233002072

public static byte[] StructToBytes(object structObj)
        {
            //得到结构体大小
            int size = Marshal.SizeOf(structObj);
            //分配结构体大小的内存空间
            IntPtr buffer = Marshal.AllocHGlobal(size);
            try
            {
                //将结构体拷到分配好的内存空间
                Marshal.StructureToPtr(structObj, buffer, false);
                //创建BYTE数组
                byte[] bytes = new byte[size];
                //从内存空间拷贝到BUTE数组
                Marshal.Copy(buffer, bytes, 0, size);
                return bytes;
            }
            finally
            {
                //释放内存空间
                Marshal.FreeHGlobal(buffer);
            }
        }

19 Source : KernelDriver.cs
with Mozilla Public License 2.0
from LibreHardwareMonitor

public bool DeviceIOControl(Kernel32.IOControlCode ioControlCode, object inBuffer)
        {
            if (_device == null)
                return false;


            return Kernel32.DeviceIoControl(_device, ioControlCode, inBuffer, inBuffer == null ? 0 : (uint)Marshal.SizeOf(inBuffer), null, 0, out uint _, IntPtr.Zero);
        }

19 Source : KernelDriver.cs
with Mozilla Public License 2.0
from LibreHardwareMonitor

public bool DeviceIOControl<T>(Kernel32.IOControlCode ioControlCode, object inBuffer, ref T outBuffer)
        {
            if (_device == null)
                return false;


            object boxedOutBuffer = outBuffer;
            bool b = Kernel32.DeviceIoControl(_device,
                                              ioControlCode,
                                              inBuffer,
                                              inBuffer == null ? 0 : (uint)Marshal.SizeOf(inBuffer),
                                              boxedOutBuffer,
                                              (uint)Marshal.SizeOf(boxedOutBuffer),
                                              out uint _,
                                              IntPtr.Zero);

            outBuffer = (T)boxedOutBuffer;
            return b;
        }

19 Source : KernelDriver.cs
with Mozilla Public License 2.0
from LibreHardwareMonitor

public bool DeviceIOControl<T>(Kernel32.IOControlCode ioControlCode, object inBuffer, ref T[] outBuffer)
        {
            if (_device == null)
                return false;


            object boxedOutBuffer = outBuffer;
            bool b = Kernel32.DeviceIoControl(_device,
                                              ioControlCode,
                                              inBuffer,
                                              inBuffer == null ? 0 : (uint)Marshal.SizeOf(inBuffer),
                                              boxedOutBuffer,
                                              (uint)(Marshal.SizeOf(typeof(T)) * outBuffer.Length),
                                              out uint _,
                                              IntPtr.Zero);

            outBuffer = (T[])boxedOutBuffer;
            return b;
        }

19 Source : KernelDriver.cs
with GNU General Public License v3.0
from lich426

public bool DeviceIOControl(Kernel32.IOControlCode ioControlCode, object inBuffer)
        {
            if (_device == null)
                return false;


            bool b = Kernel32.DeviceIoControl(_device, ioControlCode, inBuffer, inBuffer == null ? 0 : (uint)Marshal.SizeOf(inBuffer), null, 0, out uint _, IntPtr.Zero);
            return b;
        }

See More Examples