public void Install(string fileName, InstallReference objRef) { IntPtr pRef = Marshal.AllocCoTaskMem(Marshal.SizeOf(typeof(Fusion.FUSION_INSTALL_REFERENCE))); Marshal.StructureToPtr((Fusion.FUSION_INSTALL_REFERENCE)objRef, pRef, false); try { Install(fileName, pRef); } finally { Marshal.DestroyStructure(pRef, typeof(Fusion.FUSION_INSTALL_REFERENCE)); Marshal.FreeCoTaskMem(pRef); } }
/// Updates the room effects of the environment with given |reverbProbe|. /// @note This should only be called from the main Unity thread. public static void UpdateReverbProbe(ResonanceAudioReverbProbe currentReverbProbe) { if (roomPropertiesPtr == IntPtr.Zero) { // Allocate the unmanaged memory only once. roomPropertiesPtr = Marshal.AllocHGlobal(Marshal.SizeOf(roomProperties)); } UpdateRoomProperties(currentReverbProbe); Marshal.StructureToPtr(roomProperties, roomPropertiesPtr, false); SetRoomProperties(roomPropertiesPtr); // Proxy room properties. Used in calculating reflection effects. UpdateProxyRoomProperties(currentReverbProbe); Marshal.StructureToPtr(roomProperties, roomPropertiesPtr, true); SetRt60ValuesAndProxyRoomProperties(currentReverbProbe.rt60s, roomPropertiesPtr); Marshal.DestroyStructure(roomPropertiesPtr, typeof(RoomProperties)); }
public unsafe void WriteStructToMemory <T>(long address, T source) where T : struct { target.Assertions.AssertProcessAttached(); target.Assertions.AssertWritePermission(); int size = Marshal.SizeOf(typeof(T)); IntPtr structPointer = Marshal.AllocHGlobal(size); Marshal.StructureToPtr(source, structPointer, false); byte[] buffer = new byte[size]; for (int i = 0; i < size; i++) { buffer[i] = *((byte *)structPointer + i); } Marshal.DestroyStructure(structPointer, typeof(T)); WriteBytesToMemory(address, buffer); }
protected override void Dispose(bool disposing) { base.Dispose(disposing); // free the buffer if (_callbackBuffer != IntPtr.Zero) { if (_filledStruct) { Marshal.DestroyStructure(_callbackBuffer, typeof(Native.display_callback_v1)); _filledStruct = false; } Marshal.FreeHGlobal(_callbackBuffer); _callbackBuffer = IntPtr.Zero; } }
public bool SafeDecommit <T>() where T : struct { try { if (this.Size < Marshal.SizeOf(typeof(T))) { throw new InvalidCastException("Not enough unmanaged memory is allocated to contain this structure type."); } Marshal.DestroyStructure(this.Pointer, typeof(T)); return(true); } catch (Exception exception) { return(this.SetLastError(exception)); } }
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); }
void Dispose(bool disposing) { if (disposed) { return; } Marshal.DestroyStructure <T>(ptr); if (allocated) { Marshal.FreeHGlobal(ptr); } disposed = true; }
public void GetObjectForNativeVariant_ThrowsNotSupportedException() { NativeVariant variant = new NativeVariant(); IntPtr ptr = Marshal.AllocHGlobal(Marshal.SizeOf <NativeVariant>()); try { Marshal.StructureToPtr(variant, ptr, fDeleteOld: false); Assert.Throws <NotSupportedException>(() => Marshal.GetObjectForNativeVariant(ptr)); } finally { Marshal.DestroyStructure <NativeVariant>(ptr); Marshal.FreeHGlobal(ptr); } }
public static void InvokeJS <TParam>(string methodName, TParam paramStruct) { var pParms = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(TParam))); try { Marshal.StructureToPtr(paramStruct, pParms, false); var ret = WebAssemblyRuntime.InvokeJSUnmarshalled(methodName, pParms); } finally { Marshal.DestroyStructure(pParms, typeof(TParam)); Marshal.FreeHGlobal(pParms); } }
private void Dispose(bool disposing) { if (dwUnionChoice == UnionChoice.File) { var info = new WINTRUST_FILE_INFO(); Marshal.PtrToStructure(pInfoStruct, info); info.Dispose(); Marshal.DestroyStructure(pInfoStruct, typeof(WINTRUST_FILE_INFO)); } Marshal.FreeHGlobal(pInfoStruct); }
public void GetObjectForIUnknown_ThrowsNotSupportedException() { StructForIUnknown test = new StructForIUnknown(); IntPtr ptr = Marshal.AllocHGlobal(Marshal.SizeOf <StructForIUnknown>()); try { Marshal.StructureToPtr(test, ptr, fDeleteOld: false); Assert.Throws <NotSupportedException>(() => Marshal.GetObjectForIUnknown(ptr)); } finally { Marshal.DestroyStructure <StructForIUnknown>(ptr); Marshal.FreeHGlobal(ptr); } }
internal AlgorithmIdentifier(CAPI.CERT_PUBLIC_KEY_INFO keyInfo) { SafeLocalAllocHandle pKeyInfo = CAPI.LocalAlloc(CAPI.LPTR, new IntPtr(Marshal.SizeOf(typeof(CAPI.CERT_PUBLIC_KEY_INFO)))); Marshal.StructureToPtr(keyInfo, pKeyInfo.DangerousGetHandle(), false); int keyLength = (int)CAPI.CAPISafe.CertGetPublicKeyLength(CAPI.X509_ASN_ENCODING | CAPI.PKCS_7_ASN_ENCODING, pKeyInfo.DangerousGetHandle()); byte[] parameters = new byte[keyInfo.Algorithm.Parameters.cbData]; if (parameters.Length > 0) { Marshal.Copy(keyInfo.Algorithm.Parameters.pbData, parameters, 0, parameters.Length); } Marshal.DestroyStructure(pKeyInfo.DangerousGetHandle(), typeof(CAPI.CERT_PUBLIC_KEY_INFO)); pKeyInfo.Dispose(); Reset(Oid.FromOidValue(keyInfo.Algorithm.pszObjId, OidGroup.PublicKeyAlgorithm), keyLength, parameters); }
public List <Guid> GetClsIds() { var categories = new[] { new Guid("63D5F432-CFE4-11d1-B2C8-0060083BA1FB"), // DA 2.xxx new Guid("CC603642-66D7-48f1-B69A-B625E73652D7"), // DA 3.0 }; IOPCEnumGUID enumerator = null; _server.EnumClassesOfCategories(2, categories, 0, null, out enumerator); var guids = new List <Guid>(); try { var buffer = new Uri[10]; var guidSize = Marshal.SizeOf <Guid>(); int fetched = 0; do { var ptr = Marshal.AllocCoTaskMem(guidSize * buffer.Length); try { enumerator.Next(buffer.Length, ptr, out fetched); if (fetched > 0) { var p = ptr; for (int i = 0; i < fetched; i++, p += guidSize) { var v = Marshal.PtrToStructure <Guid>(p); Marshal.DestroyStructure <Guid>(p); guids.Add(v); } } } finally { Marshal.FreeCoTaskMem(ptr); } }while (fetched > 0); } catch { } finally { ComUtils.ReleaseServer(enumerator); } return(guids); }
/// <summary> /// Encode an arbitary crypto object /// </summary> /// <param name="objName">OID for the encoding</param> /// <param name="obj">The object to encode</param> /// <exception cref="Win32Exception"/> /// <returns>The encoded object</returns> private byte[] EncodeObject(string objName, object obj) { byte[] ret = new byte[0]; uint cbEncoded = 0; IntPtr pStruct = Marshal.AllocHGlobal(Marshal.SizeOf(obj)); bool bCreatedStruct = false; try { Marshal.StructureToPtr(obj, pStruct, false); bCreatedStruct = true; if (!CryptoApiMethods.CryptEncodeObject(CryptoApiMethods.CertEncoding.X509_ASN_ENCODING, objName, pStruct, null, ref cbEncoded)) { int err = Marshal.GetLastWin32Error(); // If not the error for needing more data if (err != 234) { throw new Win32Exception(err); } } ret = new byte[cbEncoded]; if (!CryptoApiMethods.CryptEncodeObject(CryptoApiMethods.CertEncoding.X509_ASN_ENCODING, objName, pStruct, ret, ref cbEncoded)) { throw new Win32Exception(Marshal.GetLastWin32Error()); } } finally { if (bCreatedStruct) { Marshal.DestroyStructure(pStruct, obj.GetType()); } if (pStruct != IntPtr.Zero) { Marshal.FreeHGlobal(pStruct); } } return(ret); }
/// <summary> /// Initializes a new instance of the <see cref="ProcessJobTracker"/> class. /// </summary> public ProcessJobTracker() { if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { return; } // The job name is optional (and can be null) but it helps with diagnostics. // If it's not null, it has to be unique. Use SysInternals' Handle command-line // utility: handle -a ChildProcessTracker string jobName = nameof(ProcessJobTracker) + Process.GetCurrentProcess().Id; this.jobHandle = CreateJobObject(IntPtr.Zero, jobName); var extendedInfo = new JOBOBJECT_EXTENDED_LIMIT_INFORMATION { BasicLimitInformation = new JOBOBJECT_BASIC_LIMIT_INFORMATION { LimitFlags = JOB_OBJECT_LIMIT_FLAGS.JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE, }, }; // This code can be a lot simpler if we use pointers, but since this class is so generally interesting // and may be copied and pasted to other projects that prefer to avoid unsafe code, we use Marshal and IntPtr's instead. int length = Marshal.SizeOf(extendedInfo); IntPtr pExtendedInfo = Marshal.AllocHGlobal(length); try { Marshal.StructureToPtr(extendedInfo, pExtendedInfo, fDeleteOld: false); try { if (!SetInformationJobObject(this.jobHandle, JOBOBJECTINFOCLASS.JobObjectExtendedLimitInformation, pExtendedInfo, (uint)length)) { throw new Win32Exception(); } } finally { Marshal.DestroyStructure <JOBOBJECT_EXTENDED_LIMIT_INFORMATION>(pExtendedInfo); } } finally { Marshal.FreeHGlobal(pExtendedInfo); } }
// Call SignerSign and SignerTimeStamp for a given thumbprint. public static void SignWithThumbprint(string appPath, string thumbprint, string timestampUrl) { IntPtr pSignerCert = IntPtr.Zero; IntPtr pSubjectInfo = IntPtr.Zero; IntPtr pSignatureInfo = IntPtr.Zero; IntPtr pProviderInfo = IntPtr.Zero; try { pSignerCert = CreateSignerCert(thumbprint); pSubjectInfo = CreateSignerSubjectInfo(appPath); pSignatureInfo = CreateSignerSignatureInfo(); SignCode(pSubjectInfo, pSignerCert, pSignatureInfo, pProviderInfo); // Only attempt to timestamp if we've got a timestampUrl. if (!string.IsNullOrEmpty(timestampUrl)) { TimeStampSignedCode(pSubjectInfo, timestampUrl); } } catch (CryptographicException ce) { // do anything with this useful information? string exception = string.Format(@"An error occurred while attempting to load the signing certificate. {0}", ce.Message); } catch (Exception e) { // do anything with this useful information? string exception = e.Message; } finally { if (pSignerCert != IntPtr.Zero) { Marshal.DestroyStructure(pSignerCert, typeof(SIGNER_CERT)); } if (pSubjectInfo != IntPtr.Zero) { Marshal.DestroyStructure(pSubjectInfo, typeof(SIGNER_SUBJECT_INFO)); } if (pSignatureInfo != IntPtr.Zero) { Marshal.DestroyStructure(pSignatureInfo, typeof(SIGNER_SIGNATURE_INFO)); } } }
private static void FreeMemory(IntPtr ptr, Type type, int count) { if (ptr == IntPtr.Zero) { return; } int size = Marshal.SizeOf(type); int pos = (int)ptr; for (int i = 0; i < count; i++) { Marshal.DestroyStructure((IntPtr)pos, type); pos += size; } Marshal.FreeHGlobal(ptr); }
/// <summary> /// Returns the current server status. /// </summary> /// <returns>The current server status.</returns> public ServerStatus GetStatus() { ServerStatus output = null; lock (this) { if (m_server == null) { throw new Exception("The remote server is not currently connected."); } // initialize arguments. IntPtr pStatus = IntPtr.Zero; // invoke COM method. try { ((IOPCServer)m_server).GetStatus(out pStatus); } catch (Exception e) { throw Interop.CreateException("IOPCServer.GetStatus", e); } if (pStatus != IntPtr.Zero) { OpcRcw.Da.OPCSERVERSTATUS status = (OpcRcw.Da.OPCSERVERSTATUS)Marshal.PtrToStructure(pStatus, typeof(OpcRcw.Da.OPCSERVERSTATUS)); output = new ServerStatus(); output.VendorInfo = status.szVendorInfo; output.ProductVersion = String.Format("{0}.{1}.{2}", status.wMajorVersion, status.wMinorVersion, status.wBuildNumber); output.ServerState = (serverState)status.dwServerState; output.StatusInfo = null; output.StartTime = Interop.GetFILETIME(OpcDa.Client.Com.Convert.GetFileTime(status.ftStartTime)); output.CurrentTime = Interop.GetFILETIME(OpcDa.Client.Com.Convert.GetFileTime(status.ftCurrentTime)); output.LastUpdateTime = Interop.GetFILETIME(OpcDa.Client.Com.Convert.GetFileTime(status.ftLastUpdateTime)); Marshal.DestroyStructure(pStatus, typeof(OpcRcw.Da.OPCSERVERSTATUS)); Marshal.FreeCoTaskMem(pStatus); pStatus = IntPtr.Zero; } } return(output); }
// Get a LOGFONT for an HFONT. public static LOGFONT GetLogFont(IntPtr hFont) { int sizeofLogFont = Marshal.SizeOf(typeof(LOGFONT)); // Allocate a LOGFONT and call GetObject to fill it in. IntPtr plogFont = Marshal.AllocHGlobal(sizeofLogFont); int numBytesStored = GetObject(hFont, sizeofLogFont, plogFont); // Convert to a .NET LOGFONT LOGFONT logfont = CreateLogFont(); Marshal.PtrToStructure(plogFont, logfont); // Cleanup. Marshal.DestroyStructure(plogFont, typeof(LOGFONT)); return(logfont); }
/// <summary> /// Connects to the specified wireless network. /// </summary> /// <remarks> /// The method returns immediately. Progress is reported through the <see cref="WlanNotification"/> event. /// </remarks> public void Connect(WlanConnectionMode connectionMode, Dot11BssType bssType, Dot11Ssid ssid, WlanConnectionFlags flags) { var connectionParams = new WlanConnectionParameters { wlanConnectionMode = connectionMode, dot11SsidPtr = Marshal.AllocHGlobal(Marshal.SizeOf(ssid)) }; Marshal.StructureToPtr(ssid, connectionParams.dot11SsidPtr, false); connectionParams.dot11BssType = bssType; connectionParams.flags = flags; Connect(connectionParams); Marshal.DestroyStructure(connectionParams.dot11SsidPtr, ssid.GetType()); Marshal.FreeHGlobal(connectionParams.dot11SsidPtr); }
/// <summary> /// Called when a draw event occurs. /// </summary> /// <param name="lParam"></param> /// <returns></returns> private IntPtr CustomDraw(IntPtr lParam) { int result; var nmlvcd = (NMLVCUSTOMDRAW)Marshal.PtrToStructure(lParam, typeof(NMLVCUSTOMDRAW)); switch (nmlvcd.nmcd.dwDrawStage) { case CDDS_PREPAINT: result = CDRF_NOTIFYITEMDRAW; break; case CDDS_ITEMPREPAINT: var index1 = nmlvcd.nmcd.dwItemSpec; var rect1 = new RECT(); SendMessage(_listView.Handle, LVM_GETITEMRECT, index1, ref rect1); if (DrawEvent != null) { DrawEvent(nmlvcd.nmcd.hdc, index1, -1, ((nmlvcd.nmcd.uItemState & CDIS_SELECTED) != 0), rect1.ToRectangleF()); } result = CDRF_NOTIFYSUBITEMDRAW; break; case CDDS_SUBITEM | CDDS_ITEMPREPAINT: var index2 = nmlvcd.nmcd.dwItemSpec; var rect2 = new RECT(); rect2.top = nmlvcd.iSubItem; rect2.left = 2; // LVIR_LABEL SendMessage(_listView.Handle, LVM_GETSUBITEMRECT, index2, ref rect2); if (DrawEvent != null) { DrawEvent(nmlvcd.nmcd.hdc, index2, nmlvcd.iSubItem, ((nmlvcd.nmcd.uItemState & CDIS_SELECTED) != 0), rect2.ToRectangleF()); } result = CDRF_SKIPDEFAULT | CDRF_NOTIFYSUBITEMDRAW; break; default: result = CDRF_DODEFAULT; break; } Marshal.DestroyStructure(lParam, typeof(NMLVCUSTOMDRAW)); return((IntPtr)result); }
public void DestroyStructure_NonGeneric_Succes() { var structure = new TestStruct(); IntPtr ptr = Marshal.AllocHGlobal(Marshal.SizeOf(structure)); try { structure.s = null; Marshal.StructureToPtr(structure, ptr, fDeleteOld: false); Marshal.DestroyStructure(ptr, typeof(TestStruct)); } finally { Marshal.FreeHGlobal(ptr); } }
/// <summary> /// Sets the value of a named property for a CNG object. /// </summary> /// <typeparam name="T">The type of value being set.</typeparam> /// <param name="hObject">A handle that represents the CNG object to set the property value for.</param> /// <param name="propertyName"> /// The name of the property to set. This can be one of the predefined <see cref="PropertyNames"/> or a custom property identifier. /// </param> /// <param name="propertyValue">The new property value.</param> /// <param name="flags">Flags to pass to <see cref="BCryptSetProperty(SafeHandle, string, byte[], int, BCryptSetPropertyFlags)"/></param> public static unsafe void BCryptSetProperty <T>(SafeHandle hObject, string propertyName, T propertyValue, BCryptSetPropertyFlags flags = BCryptSetPropertyFlags.None) { int bufferSize = Marshal.SizeOf(propertyValue); fixed(byte *valueBuffer = new byte[bufferSize]) { Marshal.StructureToPtr(propertyValue, new IntPtr(valueBuffer), false); try { BCryptSetProperty(hObject, propertyName, valueBuffer, bufferSize, flags).ThrowOnError(); } finally { Marshal.DestroyStructure(new IntPtr(valueBuffer), typeof(T)); } } }
// Call SignerSignEx and SignerTimeStampEx for a given .pfx public static void SignWithCert(string appPath, string certPath, string certPassword, string timestampUrl) { var pSignerCert = IntPtr.Zero; var pSubjectInfo = IntPtr.Zero; var pSignatureInfo = IntPtr.Zero; var pProviderInfo = IntPtr.Zero; try { X509Certificate2 cert = new X509Certificate2(certPath, certPassword); pSignerCert = CreateSignerCert(cert); pSubjectInfo = CreateSignerSubjectInfo(appPath); pSignatureInfo = CreateSignerSignatureInfo(); pProviderInfo = GetProviderInfo(cert); IntPtr signerContext; SignCode(0x0, pSubjectInfo, pSignerCert, pSignatureInfo, pProviderInfo, out signerContext); if (!string.IsNullOrEmpty(timestampUrl)) { TimeStampSignedCode(0x0, pSubjectInfo, timestampUrl, out signerContext); } } catch (Exception e) { // do anything? string exception = e.Message; } finally { if (pSignerCert != IntPtr.Zero) { Marshal.DestroyStructure(pSignerCert, typeof(SIGNER_CERT)); } if (pSubjectInfo != IntPtr.Zero) { Marshal.DestroyStructure(pSubjectInfo, typeof(SIGNER_SUBJECT_INFO)); } if (pSignatureInfo != IntPtr.Zero) { Marshal.DestroyStructure(pSignatureInfo, typeof(SIGNER_SIGNATURE_INFO)); } if (pProviderInfo != IntPtr.Zero) { Marshal.DestroyStructure(pSignatureInfo, typeof(SIGNER_PROVIDER_INFO)); } } }
public byte[] GetData() { var ptr = Marshal.AllocHGlobal(sizeof(PACKET_OID_DATA)); try { Marshal.StructureToPtr(this, ptr, false); var intPtr = (IntPtr)(ptr.ToInt64() + Marshal.OffsetOf(typeof(PACKET_OID_DATA), "Data").ToInt64()); var buffer = new byte[Length]; Marshal.Copy(intPtr, buffer, 0, (int)Length); return(buffer); } finally { Marshal.DestroyStructure(ptr, typeof(PACKET_OID_DATA)); } }
/// <summary> /// Unmarshals and deallocates an OPCHDA_ATTRIBUTE structure. /// </summary> internal static TsCHdaAttributeValueCollection GetAttributeValueCollection(IntPtr pInput, bool deallocate) { TsCHdaAttributeValueCollection output = null; if (pInput != IntPtr.Zero) { object item = Marshal.PtrToStructure(pInput, typeof(OpcRcw.Hda.OPCHDA_ATTRIBUTE)); output = GetAttributeValueCollection((OpcRcw.Hda.OPCHDA_ATTRIBUTE)item, deallocate); if (deallocate) { Marshal.DestroyStructure(pInput, typeof(OpcRcw.Hda.OPCHDA_ATTRIBUTE)); } } return(output); }
public void CleanUpNativeData(IntPtr pNativeData) { if (pNativeData == IntPtr.Zero) { return; } if (pastCallArraySizes.TryGetValue(pNativeData, out int length)) { var sz = Marshal.SizeOf(typeof(LSA_UNICODE_STRING)); for (var i = 0; i < length; i++) { Marshal.DestroyStructure(pNativeData.Offset(sz * i), typeof(LSA_UNICODE_STRING)); } pastCallArraySizes.Remove(pNativeData); } Marshal.FreeCoTaskMem(pNativeData); pNativeData = IntPtr.Zero; }
/// <summary> /// Unmarshals and deallocates an OPCHDA_ANNOTATION structure. /// </summary> internal static AnnotationValueCollection GetAnnotationValueCollection(IntPtr pInput, bool deallocate) { AnnotationValueCollection output = null; if (pInput != IntPtr.Zero) { object item = Marshal.PtrToStructure(pInput, typeof(OpcRcw.Hda.OPCHDA_ANNOTATION)); output = GetAnnotationValueCollection((OpcRcw.Hda.OPCHDA_ANNOTATION)item, deallocate); if (deallocate) { Marshal.DestroyStructure(pInput, typeof(OpcRcw.Hda.OPCHDA_ANNOTATION)); } } return(output); }
/// <summary> /// Unmarshals and deallocates an OPCHDA_MODIFIEDITEM structure. /// </summary> internal static ModifiedValueCollection GetModifiedValueCollection(IntPtr pInput, bool deallocate) { ModifiedValueCollection output = null; if (pInput != IntPtr.Zero) { object item = Marshal.PtrToStructure(pInput, typeof(OpcRcw.Hda.OPCHDA_MODIFIEDITEM)); output = GetModifiedValueCollection((OpcRcw.Hda.OPCHDA_MODIFIEDITEM)item, deallocate); if (deallocate) { Marshal.DestroyStructure(pInput, typeof(OpcRcw.Hda.OPCHDA_MODIFIEDITEM)); } } return(output); }
public bool Write <T>(IntPtr address, T value, int size = 0) { if (size == 0) { size = SizeOf(typeof(T)); } IntPtr writeBuffer = Marshal.AllocHGlobal(size); Marshal.StructureToPtr(value, writeBuffer, false); bool result = WriteProcessMemory(ProcessHandle, address, writeBuffer, size, out _); Marshal.DestroyStructure(writeBuffer, typeof(T)); Marshal.FreeHGlobal(writeBuffer); return(result); }