public unsafe void StartTransportLayerSecurity(DirectoryControlCollection controls) { IntPtr zero = IntPtr.Zero; LdapControl[] controlArray = null; IntPtr clientControls = IntPtr.Zero; LdapControl[] controlArray2 = null; IntPtr message = IntPtr.Zero; IntPtr referral = IntPtr.Zero; int serverReturnValue = 0; Uri[] uriArray = null; if (Utility.IsWin2kOS) { throw new PlatformNotSupportedException(Res.GetString("TLSNotSupported")); } if (this.connection.disposed) { throw new ObjectDisposedException(base.GetType().Name); } try { IntPtr ptr = IntPtr.Zero; IntPtr ptr6 = IntPtr.Zero; controlArray = this.connection.BuildControlArray(controls, true); int cb = Marshal.SizeOf(typeof(LdapControl)); if (controlArray != null) { zero = Marshal.AllocHGlobal((int)(Marshal.SizeOf(typeof(IntPtr)) * (controlArray.Length + 1))); for (int i = 0; i < controlArray.Length; i++) { ptr = Marshal.AllocHGlobal(cb); Marshal.StructureToPtr(controlArray[i], ptr, false); ptr6 = (IntPtr)(((long)zero) + (Marshal.SizeOf(typeof(IntPtr)) * i)); Marshal.WriteIntPtr(ptr6, ptr); } ptr6 = (IntPtr)(((long)zero) + (Marshal.SizeOf(typeof(IntPtr)) * controlArray.Length)); Marshal.WriteIntPtr(ptr6, IntPtr.Zero); } controlArray2 = this.connection.BuildControlArray(controls, false); if (controlArray2 != null) { clientControls = Marshal.AllocHGlobal((int)(Marshal.SizeOf(typeof(IntPtr)) * (controlArray2.Length + 1))); for (int j = 0; j < controlArray2.Length; j++) { ptr = Marshal.AllocHGlobal(cb); Marshal.StructureToPtr(controlArray2[j], ptr, false); ptr6 = (IntPtr)(((long)clientControls) + (Marshal.SizeOf(typeof(IntPtr)) * j)); Marshal.WriteIntPtr(ptr6, ptr); } ptr6 = (IntPtr)(((long)clientControls) + (Marshal.SizeOf(typeof(IntPtr)) * controlArray2.Length)); Marshal.WriteIntPtr(ptr6, IntPtr.Zero); } int errorCode = Wldap32.ldap_start_tls(this.connection.ldapHandle, ref serverReturnValue, ref message, zero, clientControls); if (((message != IntPtr.Zero) && (Wldap32.ldap_parse_result_referral(this.connection.ldapHandle, message, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, ref referral, IntPtr.Zero, 0) == 0)) && (referral != IntPtr.Zero)) { char ** chPtr = (char **)referral; char * chPtr2 = chPtr[0]; int index = 0; ArrayList list = new ArrayList(); while (chPtr2 != null) { string str = Marshal.PtrToStringUni((IntPtr)chPtr2); list.Add(str); index++; chPtr2 = chPtr[index]; } if (referral != IntPtr.Zero) { Wldap32.ldap_value_free(referral); referral = IntPtr.Zero; } if (list.Count > 0) { uriArray = new Uri[list.Count]; for (int k = 0; k < list.Count; k++) { uriArray[k] = new Uri((string)list[k]); } } } if (errorCode != 0) { string str2 = Res.GetString("DefaultLdapError"); if (Utility.IsResultCode((ResultCode)errorCode)) { if (errorCode == 80) { errorCode = serverReturnValue; } str2 = OperationErrorMappings.MapResultCode(errorCode); ExtendedResponse response = new ExtendedResponse(null, null, (ResultCode)errorCode, str2, uriArray) { name = "1.3.6.1.4.1.1466.20037" }; throw new TlsOperationException(response); } if (Utility.IsLdapError((LdapError)errorCode)) { str2 = LdapErrorMappings.MapResultCode(errorCode); throw new LdapException(errorCode, str2); } } } finally { if (zero != IntPtr.Zero) { for (int m = 0; m < controlArray.Length; m++) { IntPtr hglobal = Marshal.ReadIntPtr(zero, Marshal.SizeOf(typeof(IntPtr)) * m); if (hglobal != IntPtr.Zero) { Marshal.FreeHGlobal(hglobal); } } Marshal.FreeHGlobal(zero); } if (controlArray != null) { for (int n = 0; n < controlArray.Length; n++) { if (controlArray[n].ldctl_oid != IntPtr.Zero) { Marshal.FreeHGlobal(controlArray[n].ldctl_oid); } if ((controlArray[n].ldctl_value != null) && (controlArray[n].ldctl_value.bv_val != IntPtr.Zero)) { Marshal.FreeHGlobal(controlArray[n].ldctl_value.bv_val); } } } if (clientControls != IntPtr.Zero) { for (int num11 = 0; num11 < controlArray2.Length; num11++) { IntPtr ptr8 = Marshal.ReadIntPtr(clientControls, Marshal.SizeOf(typeof(IntPtr)) * num11); if (ptr8 != IntPtr.Zero) { Marshal.FreeHGlobal(ptr8); } } Marshal.FreeHGlobal(clientControls); } if (controlArray2 != null) { for (int num12 = 0; num12 < controlArray2.Length; num12++) { if (controlArray2[num12].ldctl_oid != IntPtr.Zero) { Marshal.FreeHGlobal(controlArray2[num12].ldctl_oid); } if ((controlArray2[num12].ldctl_value != null) && (controlArray2[num12].ldctl_value.bv_val != IntPtr.Zero)) { Marshal.FreeHGlobal(controlArray2[num12].ldctl_value.bv_val); } } } if (referral != IntPtr.Zero) { Wldap32.ldap_value_free(referral); } } }
private void ListenerThread() { IntPtr queuePtr; IntPtr map = CreateFileMapping(0xFFFFFFFFu, IntPtr.Zero, enumProtect.PAGE_READWRITE, 0, (uint)Marshal.SizeOf(typeof(MessageQueue)), "BadgerPacketQueue"); if (Marshal.GetLastWin32Error() == ERROR_ALREADY_EXISTS) { map = OpenFileMapping(enumFileMap.FILE_MAP_WRITE, false, "BadgerPacketQueue"); } queuePtr = MapViewOfFile(map, enumFileMap.FILE_MAP_WRITE, 0, 0, (uint)Marshal.SizeOf(typeof(MessageQueue))); Mutex queueMutex = new Mutex(false, "BadgerQueueMutex"); AutoResetEvent readyEvent = new AutoResetEvent(false); readyEvent.SafeWaitHandle = CreateEvent(IntPtr.Zero, false, // bManualReset false, // bInitialState "BadgerPacketReady"); IntPtr numElementsPtr = (IntPtr)(queuePtr.ToInt64() + Marshal.OffsetOf(typeof(MessageQueue), "num_elements").ToInt64()); IntPtr elementsPtr = (IntPtr)(queuePtr.ToInt64() + Marshal.OffsetOf(typeof(MessageQueue), "elements").ToInt64()); int elementSize = Marshal.SizeOf(typeof(MessageQueueElement)); IntPtr tmpElementPtr = Marshal.AllocHGlobal(elementSize); try { // // First off, upload softwall rules // if (!queueMutex.WaitOne(5000, false)) { Stopped(); return; } try { // Empty message queue //Marshal.WriteInt32(numElementsPtr, 0); Marshal.WriteIntPtr(queuePtr, Marshal.OffsetOf(typeof(MessageQueue), "num_softwall_rules").ToInt32(), (IntPtr)rules.Length); IntPtr p = (IntPtr)(queuePtr.ToInt64() + Marshal.OffsetOf(typeof(MessageQueue), "softwall_rules").ToInt64()); foreach (SoftwallRule rule in rules) { Marshal.StructureToPtr(rule, p, false); p = (IntPtr)(p.ToInt64() + Marshal.SizeOf(typeof(SoftwallRule))); } } finally { queueMutex.ReleaseMutex(); } // // Then start monitoring // while (listenerThread != null) { Int32 len; byte[] bytes = null; Thread.Sleep(1000); if (readyEvent.WaitOne(500, false)) { if (!queueMutex.WaitOne(5000, false)) { Stopped(); return; } try { len = Marshal.ReadInt32(numElementsPtr); if (len > 0) { bytes = new byte[len * Marshal.SizeOf(typeof(MessageQueueElement))]; Marshal.Copy(elementsPtr, bytes, 0, bytes.Length); Marshal.WriteInt32(numElementsPtr, 0); } } finally { queueMutex.ReleaseMutex(); } if (bytes != null) { MessageQueueElement[] elements = new MessageQueueElement[len]; for (int i = 0; i < len; i++) { Marshal.Copy(bytes, i * elementSize, tmpElementPtr, elementSize); elements[i] = (MessageQueueElement)Marshal.PtrToStructure(tmpElementPtr, typeof(MessageQueueElement)); } MessageElementsReceived(elements); } } } } finally { Marshal.FreeHGlobal(tmpElementPtr); } Stopped(); }
/// <summary> /// 初始化车牌识别 /// </summary> /// <returns></returns> public void Init() { try { if (_Inited) { TH_UninitPlateIDSDK(ref c_defConfig); if (c_defConfig.pFastMemory != IntPtr.Zero) { Marshal.FreeHGlobal(c_defConfig.pFastMemory); } if (c_defConfig.pMemory != IntPtr.Zero) { Marshal.FreeHGlobal(c_defConfig.pMemory); } } else { c_defConfig = new TH_PlateIDCfg(); } if (_CarplateSetting == null) { _CarplateSetting = WintoneCarplateSetting.DefaultSetting(); } c_defConfig.nFastMemorySize = _CarplateSetting.FastMemorySize; if (c_defConfig.nFastMemorySize > 0) { c_defConfig.pFastMemory = Marshal.AllocHGlobal(c_defConfig.nFastMemorySize); // stackalloc char[];// mChar; } c_defConfig.nMemorySize = _CarplateSetting.MemorySize; if (c_defConfig.nMemorySize > 0) { c_defConfig.pMemory = Marshal.AllocHGlobal(c_defConfig.nMemorySize); } c_defConfig.nMinPlateWidth = _CarplateSetting.MinPlateWidth; c_defConfig.nMaxPlateWidth = _CarplateSetting.MaxPlateWidth; c_defConfig.nMaxImageWidth = _CarplateSetting.MaxImageWidth; c_defConfig.nMaxImageHeight = _CarplateSetting.MaxImageHeight; c_defConfig.bVertCompress = (byte)(_CarplateSetting.VertCompress ? 1 : 0); c_defConfig.bIsFieldImage = (byte)(_CarplateSetting.IsFieldImage ? 1 : 0); c_defConfig.bOutputSingleFrame = (byte)(_CarplateSetting.OutputSingleFrame ? 1 : 0); //c_defConfig.bMovingImage = (byte)(_CarplateSetting.MovingImage ? 1 : 0); c_defConfig.bLeanCorrection = (byte)(_CarplateSetting.LeanCorrection ? 1 : 0); // 倾斜校正默认为关闭 c_defConfig.nImageFormat = _CarplateSetting.ImageFormat; c_defConfig.bIsNight = (byte)(_CarplateSetting.IsNight ? 1 : 0); int ret = 0; ret = TH_InitPlateIDSDK(ref c_defConfig); if (ret != 0) { _Inited = false; //MessageBox.Show(Resources.Resource1.CarPlate_Fail); Ralid.GeneralLibrary.LOG.FileLog.Log("系统", "型号W车牌识别初始化失败"); return; } ret = TH_SetProvinceOrder(_CarplateSetting.DefaultProvince, ref c_defConfig); ret = TH_SetRecogThreshold(_CarplateSetting.PlateLocate_Th, _CarplateSetting.OCR_Th, ref c_defConfig); ret = TH_SetEnabledPlateFormat(_CarplateSetting.Individual_On ? 0 : 1, ref c_defConfig); ret = TH_SetEnabledPlateFormat(_CarplateSetting.TwoRowYellow_On ? 2 : 3, ref c_defConfig); ret = TH_SetEnabledPlateFormat(_CarplateSetting.ArmPolice_On ? 4 : 5, ref c_defConfig); ret = TH_SetEnabledPlateFormat(_CarplateSetting.TwoRowArmy_On ? 6 : 7, ref c_defConfig); ret = TH_SetEnabledPlateFormat(_CarplateSetting.Tractor_On ? 8 : 9, ref c_defConfig); ret = TH_SetEnabledPlateFormat(_CarplateSetting.Only_TwoRowYellow_On ? 10 : 11, ref c_defConfig); ret = TH_SetEnabledPlateFormat(_CarplateSetting.Embassy_On ? 12 : 13, ref c_defConfig); ret = TH_SetEnabledPlateFormat(_CarplateSetting.Only_Location_On ? 14 : 15, ref c_defConfig); ret = TH_SetEnabledPlateFormat(_CarplateSetting.TwoRowArmPolice_On ? 16 : 17, ref c_defConfig); _Inited = true; } catch (Exception ex) { _Inited = false; Ralid.GeneralLibrary.ExceptionHandling.ExceptionPolicy.HandleException(ex); } }
/// <summary> /// Calls DPAPI CryptUnprotectData to decrypt ciphertext bytes. /// </summary> /// <param name="cipherTextBytes"> /// Encrypted data. /// </param> /// <param name="entropyBytes"> /// Optional entropy, which is required if it was specified during /// encryption. /// </param> /// <param name="description"> /// Returned description of data specified during encryption. /// </param> /// <returns> /// Decrypted data bytes. /// </returns> /// <remarks> /// When decrypting data, it is not necessary to specify which /// type of encryption key to use: user-specific or /// machine-specific; DPAPI will figure it out by looking at /// the signature of encrypted data. /// </remarks> public static byte[] Decrypt(byte[] cipherTextBytes, byte[] entropyBytes, out string description) { // Create BLOBs to hold data. DATA_BLOB plainTextBlob = new DATA_BLOB(); DATA_BLOB cipherTextBlob = new DATA_BLOB(); DATA_BLOB entropyBlob = new DATA_BLOB(); // We only need prompt structure because it is a required // parameter. CRYPTPROTECT_PROMPTSTRUCT prompt = new CRYPTPROTECT_PROMPTSTRUCT(); InitPrompt(ref prompt); // Initialize description string. description = String.Empty; try { // Convert ciphertext bytes into a BLOB structure. try { InitBLOB(cipherTextBytes, ref cipherTextBlob); } catch (Exception ex) { throw new Exception( "Cannot initialize ciphertext BLOB.", ex); } // Convert entropy bytes into a BLOB structure. try { InitBLOB(entropyBytes, ref entropyBlob); } catch (Exception ex) { throw new Exception( "Cannot initialize entropy BLOB.", ex); } // Disable any types of UI. CryptUnprotectData does not // mention CRYPTPROTECT_LOCAL_MACHINE flag in the list of // supported flags so we will not set it up. int flags = CRYPTPROTECT_UI_FORBIDDEN; // Call DPAPI to decrypt data. bool success = CryptUnprotectData(ref cipherTextBlob, ref description, ref entropyBlob, IntPtr.Zero, ref prompt, flags, ref plainTextBlob); // Check the result. if (!success) { // If operation failed, retrieve last Win32 error. int errCode = Marshal.GetLastWin32Error(); // Win32Exception will contain error message corresponding // to the Windows error code. throw new Exception( "CryptUnprotectData failed.", new Win32Exception(errCode)); } // Allocate memory to hold plaintext. byte[] plainTextBytes = new byte[plainTextBlob.cbData]; // Copy ciphertext from the BLOB to a byte array. Marshal.Copy(plainTextBlob.pbData, plainTextBytes, 0, plainTextBlob.cbData); // Return the result. return(plainTextBytes); } catch (Exception ex) { throw new Exception("DPAPI was unable to decrypt data.", ex); } // Free all memory allocated for BLOBs. finally { if (plainTextBlob.pbData != IntPtr.Zero) { Marshal.FreeHGlobal(plainTextBlob.pbData); } if (cipherTextBlob.pbData != IntPtr.Zero) { Marshal.FreeHGlobal(cipherTextBlob.pbData); } if (entropyBlob.pbData != IntPtr.Zero) { Marshal.FreeHGlobal(entropyBlob.pbData); } } }
internal static void Free(cef_pdf_print_callback_t *ptr) { Marshal.FreeHGlobal((IntPtr)ptr); }
int PutContent(IntPtr h, NormalStruct Data) { int res = 0; Egal.ccn_charbuf Nm = new Egal.ccn_charbuf(); Nm = (Egal.ccn_charbuf)Marshal.PtrToStructure(Data.nm, typeof(Egal.ccn_charbuf)); IntPtr uri = Egal.ccn_charbuf_create(); Egal.ccn_uri_append(uri, Nm.buf, Nm.length, 0); IntPtr name = Egal.SyncCopyName(Data.nm); IntPtr cb = Egal.ccn_charbuf_create(); IntPtr cob = Egal.ccn_charbuf_create(); Egal.ccn_charbuf_append(cb, Data.value, Data.vSize); Egal.ccn_charbuf Cb = new Egal.ccn_charbuf(); Cb = (Egal.ccn_charbuf)Marshal.PtrToStructure(cb, typeof(Egal.ccn_charbuf)); Egal.ccn_signing_params Sp = new Egal.ccn_signing_params(CCN.CCN_API_VERSION); Sp.sp_flags |= SP.signingparameters.CCN_SP_FINAL_BLOCK; IntPtr pSp = Marshal.AllocHGlobal(Marshal.SizeOf(Sp)); Marshal.StructureToPtr(Sp, pSp, true); /* * // test zone * Egal.ccn_signing_params Test = new Egal.ccn_signing_params(CCN.CCN_API_VERSION); * IntPtr pTest = Marshal.AllocHGlobal(Marshal.SizeOf(Test)); * Marshal.StructureToPtr(Test, pTest, true); * IntPtr a = IntPtr.Zero; * IntPtr b = IntPtr.Zero; * IntPtr c = IntPtr.Zero; * res = Egal.ccn_chk_signing_params(h, pSp, pTest, ref a, ref b, ref c); * print ("check result: " + res); * // test zone end */ // Data.ccn, Cb.buf, Data.vSize is correct res |= Egal.ccn_sign_content(h, cob, name, pSp, Cb.buf, Data.vSize); if (res < 0) { print("sign content error."); } Egal.ccn_charbuf Cob = new Egal.ccn_charbuf(); Cob = (Egal.ccn_charbuf)Marshal.PtrToStructure(cob, typeof(Egal.ccn_charbuf)); res |= Egal.ccn_put(Data.ccn, Cob.buf, Cob.length); if (res < 0) { print("ccn_put error."); } // cleanup Egal.ccn_charbuf_destroy(ref uri); Egal.ccn_charbuf_destroy(ref name); Egal.ccn_charbuf_destroy(ref cb); Egal.ccn_charbuf_destroy(ref cob); Marshal.FreeHGlobal(pSp); return(res); }
private void onLoadController(WVR_DeviceType type) { mLoadingState = LoadingState.LoadingState_LOADING; PrintDebugLog("Pos: " + this.transform.localPosition.x + " " + this.transform.localPosition.y + " " + this.transform.localPosition.z); PrintDebugLog("Rot: " + this.transform.localEulerAngles); if (Interop.WVR_GetWaveRuntimeVersion() < 2) { PrintDebugLog("onLoadController in old service"); if (defaultModel != null) { controllerSpawned = Instantiate(defaultModel, this.transform); controllerSpawned.transform.parent = this.transform; } mLoadingState = LoadingState.LoadingState_NOT_LOADED; return; } string parameterName = "GetRenderModelName"; ptrParameterName = Marshal.StringToHGlobalAnsi(parameterName); ptrResult = Marshal.AllocHGlobal(64); uint resultVertLength = 64; uint retOfRenderModel = Interop.WVR_GetParameters(type, ptrParameterName, ptrResult, resultVertLength); if (retOfRenderModel == 0) { PrintDebugLog("Can not find render model."); if (defaultModel != null) { PrintDebugLog("Can't load controller model from DS, load default model"); controllerSpawned = Instantiate(defaultModel, this.transform); controllerSpawned.transform.parent = this.transform; mLoadingState = LoadingState.LoadingState_NOT_LOADED; } Marshal.FreeHGlobal(ptrParameterName); Marshal.FreeHGlobal(ptrResult); return; } renderModelName = Marshal.PtrToStringAnsi(ptrResult); int deviceIndex = -1; parameterName = "backdoor_get_device_index"; ptrParameterName = Marshal.StringToHGlobalAnsi(parameterName); IntPtr ptrResultDeviceIndex = Marshal.AllocHGlobal(2); Interop.WVR_GetParameters(type, ptrParameterName, ptrResultDeviceIndex, 2); int _out = 0; bool _ret = int.TryParse(Marshal.PtrToStringAnsi(ptrResultDeviceIndex), out _out); if (_ret) { deviceIndex = _out; } PrintInfoLog("get controller id from runtime is " + renderModelName + ", deviceIndex = " + deviceIndex); // 1. check if there are assets in private folder string renderModelFolderPath = Interop.WVR_DeployRenderModelAssets(deviceIndex, renderModelName); mLoadingState = (renderModelFolderPath != "") ? LoadingState.LoadingState_LOADING : LoadingState.LoadingState_NOT_LOADED; if (renderModelFolderPath != "") { bool retModel = false; modelResource = null; renderModelNamePath = renderModelFolderPath + "Model"; retModel = WaveVR_ControllerResourceHolder.Instance.addRenderModel(renderModelName, renderModelNamePath, modelSpecify, mergeToOneBone); if (retModel) { PrintDebugLog("Add " + renderModelName + " with " + modelSpecify + " model sucessfully!"); } modelResource = WaveVR_ControllerResourceHolder.Instance.getRenderModelResource(renderModelName, modelSpecify, mergeToOneBone); if ((modelResource == null) && (modelSpecify == ModelSpecify.MS_NonDominant)) { retModel = WaveVR_ControllerResourceHolder.Instance.addRenderModel(renderModelName, renderModelNamePath, ModelSpecify.MS_Dominant, mergeToOneBone); if (retModel) { PrintDebugLog("Add " + renderModelName + " Dominant model sucessfully!"); } modelResource = WaveVR_ControllerResourceHolder.Instance.getRenderModelResource(renderModelName, ModelSpecify.MS_Dominant, mergeToOneBone); } if (modelResource != null) { mLoadingState = LoadingState.LoadingState_LOADING; PrintDebugLog("Starting load " + renderModelName + " with <" + modelResource.modelSpecify + "> model!"); ImgMaterial = new Material(Shader.Find("Unlit/Texture")); wfef = new WaitForEndOfFrame(); StartCoroutine(SpawnRenderModel()); } else { PrintDebugLog("Model is null!"); if (defaultModel != null) { PrintDebugLog("Can't load controller model from DS, load default model"); controllerSpawned = Instantiate(defaultModel, this.transform); controllerSpawned.transform.parent = this.transform; mLoadingState = LoadingState.LoadingState_LOADED; } } } Marshal.FreeHGlobal(ptrParameterName); Marshal.FreeHGlobal(ptrResult); }
public static bool Find(Guid target, ref string path, ref string instanceId, int instance = 0) { var detailDataBuffer = IntPtr.Zero; var deviceInfoSet = IntPtr.Zero; try { SP_DEVINFO_DATA deviceInterfaceData = new SP_DEVINFO_DATA(), da = new SP_DEVINFO_DATA(); int bufferSize = 0, memberIndex = 0; deviceInfoSet = SetupDiGetClassDevs(ref target, IntPtr.Zero, IntPtr.Zero, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE); deviceInterfaceData.cbSize = da.cbSize = Marshal.SizeOf(deviceInterfaceData); while (SetupDiEnumDeviceInterfaces(deviceInfoSet, IntPtr.Zero, ref target, memberIndex, ref deviceInterfaceData)) { SetupDiGetDeviceInterfaceDetail(deviceInfoSet, ref deviceInterfaceData, IntPtr.Zero, 0, ref bufferSize, ref da); { detailDataBuffer = Marshal.AllocHGlobal(bufferSize); Marshal.WriteInt32(detailDataBuffer, (IntPtr.Size == 4) ? (4 + Marshal.SystemDefaultCharSize) : 8); if (SetupDiGetDeviceInterfaceDetail(deviceInfoSet, ref deviceInterfaceData, detailDataBuffer, bufferSize, ref bufferSize, ref da)) { var pDevicePathName = detailDataBuffer + 4; path = (Marshal.PtrToStringAuto(pDevicePathName) ?? string.Empty).ToUpper(); if (memberIndex == instance) { var nBytes = 256; var ptrInstanceBuf = Marshal.AllocHGlobal(nBytes); CM_Get_Device_ID(da.Flags, ptrInstanceBuf, nBytes, 0); instanceId = (Marshal.PtrToStringAuto(ptrInstanceBuf) ?? string.Empty).ToUpper(); Marshal.FreeHGlobal(ptrInstanceBuf); return(true); } } else { Marshal.FreeHGlobal(detailDataBuffer); } } memberIndex++; } } finally { if (deviceInfoSet != IntPtr.Zero) { SetupDiDestroyDeviceInfoList(deviceInfoSet); } } return(false); }
private bool LoadPcx(int offset, SFFSUBHEADER subHeader, byte[] source, out KeyValuePair<PCXHEADER, PCXDATA> dataPair) { if ((offset < 0) || (offset >= source.Length)) { dataPair = new KeyValuePair<PCXHEADER, PCXDATA>(); return false; } PCXHEADER header = new PCXHEADER(); int bufSize = Marshal.SizeOf(header); if (offset + bufSize > source.Length) { dataPair = new KeyValuePair<PCXHEADER, PCXDATA>(); return false; } IntPtr buf = Marshal.AllocHGlobal(bufSize); try { Marshal.Copy(source, offset, buf, bufSize); header = (PCXHEADER)Marshal.PtrToStructure(buf, typeof(PCXHEADER)); } finally { Marshal.FreeHGlobal(buf); } if (header.BPP == 0) { dataPair = new KeyValuePair<PCXHEADER, PCXDATA>(); return true; } offset += bufSize; int pcxBufSz = (int)subHeader.LenghtOfSubheader - 127; if (pcxBufSz <= 0) { dataPair = new KeyValuePair<PCXHEADER, PCXDATA>(); return true; } if (offset + pcxBufSz > source.Length) { dataPair = new KeyValuePair<PCXHEADER, PCXDATA>(); return true; } byte[] pcxBuf = new byte[pcxBufSz]; Buffer.BlockCopy(source, offset, pcxBuf, 0, pcxBufSz); offset += pcxBufSz; if (offset >= source.Length) { dataPair = new KeyValuePair<PCXHEADER, PCXDATA>(); return false; } header.widht = (ushort)(header.widht - header.x + 1); header.height = (ushort)(header.height - header.y + 1); //byte[] dst = DecodePcxData(offset, header, pcxBuf); byte[] dst = DecodePcxData(0, header, pcxBuf); pcxBuf = null; if ((dst == null) || (dst.Length <= 0)) { // empty dataPair = new KeyValuePair<PCXHEADER, PCXDATA>(); return true; } PCXDATA pcxData = new PCXDATA(); pcxData.data = dst; pcxData.pallet = null; // 判断是不是9000,1 // if (subHeader.GroubNumber == 9000 && subHeader.ImageNumber == 1) { // pcxData.palletLink = m_currentLink; /*} else*/ { offset -= 768; //eat empty 8bit offset++; byte s = source [offset++]; if ((s == 12) && !subHeader.PalletSame && !HasNormalPallet && header.NPlanes <= 1) { // if (!subHeader.PalletSame && !HasNormalPallet && header.NPlanes <= 1) // load pallet pcxData.pallet = new Color32[256]; for (int i = 0; i < 256; ++i) { byte r = source [offset++]; byte g = source [offset++]; byte b = source [offset++]; byte a; if (i == 0) a = 0; else { if ((r == pcxData.pallet [i - 1].r) && (g == pcxData.pallet [i - 1].g) && (b == pcxData.pallet [i - 1].b)) a = 0; else a = 0xFF; } pcxData.pallet [i] = new Color32 (r, g, b, a); } m_currentLink = new KeyValuePair<short, short> (subHeader.GroubNumber, subHeader.ImageNumber); } else pcxData.palletLink = m_currentLink; } dataPair = new KeyValuePair<PCXHEADER, PCXDATA>(header, pcxData); return true; }
/// <summary> /// Creates a junction point from the specified directory to the specified target directory. /// </summary> /// <remarks> /// Only works on NTFS. /// </remarks> /// <param name="junctionPoint">The junction point path</param> /// <param name="targetDir">The target directory</param> /// <param name="overwrite">If true overwrites an existing reparse point or empty directory</param> /// <exception cref="IOException"> /// Thrown when the junction point could not be created or when /// an existing directory was found and <paramref name="overwrite" /> if false /// </exception> public static void Create(string junctionPoint, string targetDir, bool overwrite) { targetDir = Path.GetFullPath(targetDir); if (!Directory.Exists(targetDir)) { throw new IOException("Target path does not exist or is not a directory."); } if (Directory.Exists(junctionPoint)) { if (!overwrite) { throw new IOException("Directory already exists and overwrite parameter is false."); } } else { Directory.CreateDirectory(junctionPoint); } using (var handle = OpenReparsePoint(junctionPoint, EFileAccess.GenericWrite)) { var targetDirBytes = Encoding.Unicode.GetBytes(NonInterpretedPathPrefix + Path.GetFullPath(targetDir)); var reparseDataBuffer = new REPARSE_DATA_BUFFER { ReparseTag = IO_REPARSE_TAG_MOUNT_POINT, ReparseDataLength = (ushort)(targetDirBytes.Length + 12), SubstituteNameOffset = 0, SubstituteNameLength = (ushort)targetDirBytes.Length, PrintNameOffset = (ushort)(targetDirBytes.Length + 2), PrintNameLength = 0, PathBuffer = new byte[0x3ff0] }; Array.Copy(targetDirBytes, reparseDataBuffer.PathBuffer, targetDirBytes.Length); var inBufferSize = Marshal.SizeOf(reparseDataBuffer); var inBuffer = Marshal.AllocHGlobal(inBufferSize); try { Marshal.StructureToPtr(reparseDataBuffer, inBuffer, false); int bytesReturned; var result = DeviceIoControl(handle.DangerousGetHandle(), FSCTL_SET_REPARSE_POINT, inBuffer, targetDirBytes.Length + 20, IntPtr.Zero, 0, out bytesReturned, IntPtr.Zero); if (!result) { ThrowLastWin32Error("Unable to create junction point."); } } finally { Marshal.FreeHGlobal(inBuffer); } } }
private static void TestMarshalStructAPIs() { Console.WriteLine("Testing Marshal APIs for structs"); BlittableStruct bs = new BlittableStruct() { FirstField = 1.0f, SecondField = 2.0f, ThirdField = 3 }; int bs_size = Marshal.SizeOf <BlittableStruct>(bs); ThrowIfNotEquals(40, bs_size, "Marshal.SizeOf<BlittableStruct> failed"); IntPtr bs_memory = Marshal.AllocHGlobal(bs_size); try { Marshal.StructureToPtr <BlittableStruct>(bs, bs_memory, false); BlittableStruct bs2 = Marshal.PtrToStructure <BlittableStruct>(bs_memory); ThrowIfNotEquals(true, bs2.FirstField == 1.0f && bs2.SecondField == 2.0f && bs2.ThirdField == 3, "BlittableStruct marshalling Marshal API failed"); IntPtr offset = Marshal.OffsetOf <BlittableStruct>("SecondField"); ThrowIfNotEquals(new IntPtr(12), offset, "Struct marshalling OffsetOf failed."); } finally { Marshal.FreeHGlobal(bs_memory); } NonBlittableStruct ts = new NonBlittableStruct() { f1 = 100, f2 = true, f3 = false, f4 = true }; int size = Marshal.SizeOf <NonBlittableStruct>(ts); ThrowIfNotEquals(16, size, "Marshal.SizeOf<NonBlittableStruct> failed"); IntPtr memory = Marshal.AllocHGlobal(size); try { Marshal.StructureToPtr <NonBlittableStruct>(ts, memory, false); NonBlittableStruct ts2 = Marshal.PtrToStructure <NonBlittableStruct>(memory); ThrowIfNotEquals(true, ts2.f1 == 100 && ts2.f2 == true && ts2.f3 == false && ts2.f4 == true, "NonBlittableStruct marshalling Marshal API failed"); IntPtr offset = Marshal.OffsetOf <NonBlittableStruct>("f2"); ThrowIfNotEquals(new IntPtr(4), offset, "Struct marshalling OffsetOf failed."); } finally { Marshal.FreeHGlobal(memory); } BlittableClass bc = new BlittableClass() { f1 = 100, f2 = 12345678, f3 = 999, f4 = -4 }; int bc_size = Marshal.SizeOf <BlittableClass>(bc); ThrowIfNotEquals(24, bc_size, "Marshal.SizeOf<BlittableClass> failed"); IntPtr bc_memory = Marshal.AllocHGlobal(bc_size); try { Marshal.StructureToPtr <BlittableClass>(bc, bc_memory, false); BlittableClass bc2 = Marshal.PtrToStructure <BlittableClass>(bc_memory); ThrowIfNotEquals(true, bc2.f1 == 100 && bc2.f2 == 12345678 && bc2.f3 == 999 && bc2.f4 == -4, "BlittableClass marshalling Marshal API failed"); } finally { Marshal.FreeHGlobal(bc_memory); } NonBlittableClass nbc = new NonBlittableClass() { f1 = false, f2 = true, f3 = 42 }; int nbc_size = Marshal.SizeOf <NonBlittableClass>(nbc); ThrowIfNotEquals(12, nbc_size, "Marshal.SizeOf<NonBlittableClass> failed"); IntPtr nbc_memory = Marshal.AllocHGlobal(nbc_size); try { Marshal.StructureToPtr <NonBlittableClass>(nbc, nbc_memory, false); NonBlittableClass nbc2 = Marshal.PtrToStructure <NonBlittableClass>(nbc_memory); ThrowIfNotEquals(true, nbc2.f1 == false && nbc2.f2 == true && nbc2.f3 == 42, "NonBlittableClass marshalling Marshal API failed"); } finally { Marshal.FreeHGlobal(nbc_memory); } }
internal static void Free(cef_render_process_handler_t *ptr) { Marshal.FreeHGlobal((IntPtr)ptr); }
public static void ReleaseData(IntPtr ptr) { Marshal.FreeHGlobal(ptr); }
private int PrivateShow(IntPtr hwndOwner, out bool verificationFlagChecked, out int radioButtonResult) { verificationFlagChecked = false; radioButtonResult = 0; int result; if (!TaskDialog.IsAvailable) { // Hand it off to emulator. _emulateTaskDialog = new EmulateTaskDialog(this); try { if (hwndOwner == IntPtr.Zero) { _emulateTaskDialog.ShowDialog(); } else { _emulateTaskDialog.ShowDialog(new WindowHandleWrapper(hwndOwner)); } verificationFlagChecked = _emulateTaskDialog.TaskDialogVerificationFlagChecked; radioButtonResult = _emulateTaskDialog.TaskDialogRadioButtonResult; result = _emulateTaskDialog.TaskDialogResult; } finally { _emulateTaskDialog.Dispose(); _emulateTaskDialog = null; } return(result); } NativeMethods.TASKDIALOGCONFIG config = new NativeMethods.TASKDIALOGCONFIG(); try { config.cbSize = (uint)Marshal.SizeOf(typeof(NativeMethods.TASKDIALOGCONFIG)); config.hwndParent = hwndOwner; config.dwFlags = _flags; config.dwCommonButtons = CommonButtons; config.pszWindowTitle = WindowTitle; config.MainIcon = (IntPtr)MainIcon; if (CustomMainIcon != null) { config.dwFlags |= NativeMethods.TASKDIALOG_FLAGS.TDF_USE_HICON_MAIN; config.MainIcon = CustomMainIcon.Handle; } if (!string.IsNullOrEmpty(MainInstruction)) { config.pszMainInstruction = MainInstruction; } if (!string.IsNullOrEmpty(Content)) { config.pszContent = Content; } TaskDialogButton[] customButtons = Buttons.ToArray(); if (customButtons.Length > 0) { // Hand marshal the buttons array. int elementSize = Marshal.SizeOf(typeof(TaskDialogButton)); config.pButtons = Marshal.AllocHGlobal(elementSize * customButtons.Length); for (int i = 0; i < customButtons.Length; i++) { Marshal.StructureToPtr(customButtons[i], (IntPtr)((long)config.pButtons + elementSize * i), false); config.cButtons++; } } TaskDialogButton[] customRadioButtons = RadioButtons.ToArray(); if (customRadioButtons.Length > 0) { // Hand marshal the buttons array. int elementSize = Marshal.SizeOf(typeof(TaskDialogButton)); config.pRadioButtons = Marshal.AllocHGlobal(elementSize * customRadioButtons.Length); for (int i = 0; i < customRadioButtons.Length; i++) { Marshal.StructureToPtr(customRadioButtons[i], (IntPtr)((long)config.pRadioButtons + (elementSize * i)), false); config.cRadioButtons++; } } config.nDefaultButton = DefaultButton; config.nDefaultRadioButton = DefaultRadioButton; if (!string.IsNullOrEmpty(VerificationText)) { config.pszVerificationText = VerificationText; } if (!string.IsNullOrEmpty(ExpandedInformation)) { config.pszExpandedInformation = ExpandedInformation; } if (!string.IsNullOrEmpty(ExpandedControlText)) { config.pszExpandedControlText = ExpandedControlText; } if (!string.IsNullOrEmpty(CollapsedControlText)) { config.pszCollapsedControlText = CollapsedControlText; } config.FooterIcon = (IntPtr)FooterIcon; if (CustomFooterIcon != null) { config.dwFlags |= NativeMethods.TASKDIALOG_FLAGS.TDF_USE_HICON_FOOTER; config.FooterIcon = CustomFooterIcon.Handle; } if (!string.IsNullOrEmpty(Footer)) { config.pszFooter = Footer; } // If our user has asked for a callback then we need to ask for one to // translate to the friendly version. if (Callback != null) { config.pfCallback = PrivateCallback; } config.cxWidth = Width; using (new ActivationContext()) { // The call all this mucking about is here for. NativeMethods.TaskDialogIndirect(ref config, out result, out radioButtonResult, out verificationFlagChecked); } } finally { // Free the unmanged memory needed for the button arrays. // There is the possiblity of leaking memory if the app-domain is destroyed in a non clean way // and the hosting OS process is kept alive but fixing this would require using hardening techniques // that are not required for the users of this class. if (config.pButtons != IntPtr.Zero) { int elementSize = Marshal.SizeOf(typeof(TaskDialogButton)); for (int i = 0; i < config.cButtons; i++) { Marshal.DestroyStructure((IntPtr)((long)config.pButtons + (elementSize * i)), typeof(TaskDialogButton)); } Marshal.FreeHGlobal(config.pButtons); } if (config.pRadioButtons != IntPtr.Zero) { int elementSize = Marshal.SizeOf(typeof(TaskDialogButton)); for (int i = 0; i < config.cRadioButtons; i++) { Marshal.DestroyStructure((IntPtr)((long)config.pRadioButtons + (elementSize * i)), typeof(TaskDialogButton)); } Marshal.FreeHGlobal(config.pRadioButtons); } } return(result); }
/// <summary>Installs the service by writing service application information to the registry. This method is meant to be used by installation tools, which process the appropriate methods automatically.</summary> /// <param name="stateSaver">An <see cref="T:System.Collections.IDictionary" /> that contains the context information associated with the installation. </param> /// <exception cref="T:System.InvalidOperationException">The installation does not contain a <see cref="T:System.ServiceProcess.ServiceProcessInstaller" /> for the executable.-or- The file name for the assembly is null or an empty string.-or- The service name is invalid.-or- The Service Control Manager could not be opened. </exception> /// <exception cref="T:System.ArgumentException">The display name for the service is more than 255 characters in length.</exception> /// <exception cref="T:System.ComponentModel.Win32Exception">The system could not generate a handle to the service. -or-A service with that name is already installed.</exception> /// <PermissionSet> /// <IPermission class="System.Security.Permissions.FileIOPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true" /> /// <IPermission class="System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Flags="UnmanagedCode" /> /// <IPermission class="System.Security.Permissions.UIPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true" /> /// </PermissionSet> public override void Install(IDictionary stateSaver) { base.Context.LogMessage(Res.GetString("InstallingService", this.ServiceName)); try { ServiceInstaller.CheckEnvironment(); string servicesStartName = null; string password = null; ServiceProcessInstaller serviceProcessInstaller = null; if (base.Parent is ServiceProcessInstaller) { serviceProcessInstaller = (ServiceProcessInstaller)base.Parent; } else { int num = 0; while (num < base.Parent.Installers.Count) { if (!(base.Parent.Installers[num] is ServiceProcessInstaller)) { num++; continue; } serviceProcessInstaller = (ServiceProcessInstaller)base.Parent.Installers[num]; break; } } if (serviceProcessInstaller == null) { throw new InvalidOperationException(Res.GetString("NoInstaller")); } switch (serviceProcessInstaller.Account) { case ServiceAccount.LocalService: servicesStartName = "NT AUTHORITY\\LocalService"; break; case ServiceAccount.NetworkService: servicesStartName = "NT AUTHORITY\\NetworkService"; break; case ServiceAccount.User: servicesStartName = serviceProcessInstaller.Username; password = serviceProcessInstaller.Password; break; } string text = base.Context.Parameters["assemblypath"]; if (string.IsNullOrEmpty(text)) { throw new InvalidOperationException(Res.GetString("FileName")); } if (text.IndexOf('"') == -1) { text = "\"" + text + "\""; } if (!ServiceInstaller.ValidateServiceName(this.ServiceName)) { throw new InvalidOperationException(Res.GetString("ServiceName", this.ServiceName, 80.ToString(CultureInfo.CurrentCulture))); } if (this.DisplayName.Length > 255) { throw new ArgumentException(Res.GetString("DisplayNameTooLong", this.DisplayName)); } string dependencies = null; if (this.ServicesDependedOn.Length != 0) { StringBuilder stringBuilder = new StringBuilder(); for (int i = 0; i < this.ServicesDependedOn.Length; i++) { string text2 = this.ServicesDependedOn[i]; try { text2 = new ServiceController(text2, ".").ServiceName; } catch { } stringBuilder.Append(text2); stringBuilder.Append('\0'); } stringBuilder.Append('\0'); dependencies = stringBuilder.ToString(); } IntPtr intPtr = SafeNativeMethods.OpenSCManager(null, null, 983103); IntPtr intPtr2 = IntPtr.Zero; if (intPtr == IntPtr.Zero) { throw new InvalidOperationException(Res.GetString("OpenSC", "."), new Win32Exception()); } int serviceType = 16; int num2 = 0; for (int j = 0; j < base.Parent.Installers.Count; j++) { if (base.Parent.Installers[j] is ServiceInstaller) { num2++; if (num2 > 1) { break; } } } if (num2 > 1) { serviceType = 32; } try { intPtr2 = NativeMethods.CreateService(intPtr, this.ServiceName, this.DisplayName, 983551, serviceType, (int)this.StartType, 1, text, null, IntPtr.Zero, dependencies, servicesStartName, password); if (intPtr2 == IntPtr.Zero) { throw new Win32Exception(); } if (this.Description.Length != 0) { NativeMethods.SERVICE_DESCRIPTION sERVICE_DESCRIPTION = default(NativeMethods.SERVICE_DESCRIPTION); sERVICE_DESCRIPTION.description = Marshal.StringToHGlobalUni(this.Description); bool num3 = NativeMethods.ChangeServiceConfig2(intPtr2, 1u, ref sERVICE_DESCRIPTION); Marshal.FreeHGlobal(sERVICE_DESCRIPTION.description); if (!num3) { throw new Win32Exception(); } } if (Environment.OSVersion.Version.Major > 5 && this.StartType == ServiceStartMode.Automatic) { NativeMethods.SERVICE_DELAYED_AUTOSTART_INFO sERVICE_DELAYED_AUTOSTART_INFO = default(NativeMethods.SERVICE_DELAYED_AUTOSTART_INFO); sERVICE_DELAYED_AUTOSTART_INFO.fDelayedAutostart = this.DelayedAutoStart; if (!NativeMethods.ChangeServiceConfig2(intPtr2, 3u, ref sERVICE_DELAYED_AUTOSTART_INFO)) { throw new Win32Exception(); } } stateSaver["installed"] = true; } finally { if (intPtr2 != IntPtr.Zero) { SafeNativeMethods.CloseServiceHandle(intPtr2); } SafeNativeMethods.CloseServiceHandle(intPtr); } base.Context.LogMessage(Res.GetString("InstallOK", this.ServiceName)); } finally { base.Install(stateSaver); } }
private bool Load(byte[] bytes) { mPcxDataMap.Clear(); if (mSubHeaders != null) mSubHeaders.Clear(); if ((bytes == null) || (bytes.Length <= 0)) { mIsVaild = false; return false; } // 判断是否是v2的文件 if (bytes.Length < 16) { mIsVaild = false; return false; } byte v1 = bytes[15]; byte v2; byte v3; byte v4; if (v1 == 2) { SFFHEADERv2 header = new SFFHEADERv2(); int headerSize = Marshal.SizeOf(header); IntPtr headerBuffer = Marshal.AllocHGlobal(headerSize); try { Marshal.Copy(bytes, 0, headerBuffer, headerSize); header = (SFFHEADERv2)Marshal.PtrToStructure(headerBuffer, typeof(SFFHEADERv2)); } finally { Marshal.FreeHGlobal(headerBuffer); } MemoryStream stream = new MemoryStream (bytes); try { // SFFHEADERv2 header = SFFHEADERv2.LoadFromStream (stream); int comp = string.Compare(header.signature, _cElecbyteSpr, true); if (comp != 0) return false; v1 = header.verlo2; v2 = header.verlo; v3 = header.verhi2; v4 = header.verhi; if (!LoadSubFilesV2(header, stream)) return false; } finally { stream.Close (); stream.Dispose (); } } else if (v1 == 1) { SFFHEADER header = new SFFHEADER(); int headerSize = Marshal.SizeOf(header); IntPtr headerBuffer = Marshal.AllocHGlobal(headerSize); try { Marshal.Copy(bytes, 0, headerBuffer, headerSize); header = (SFFHEADER)Marshal.PtrToStructure(headerBuffer, typeof(SFFHEADER)); } finally { Marshal.FreeHGlobal(headerBuffer); } if (string.Compare(header.signature, _cElecbyteSpr, true) != 0) return false; v1 = header.verlo2; v2 = header.verlo; v3 = header.verhi2; v4 = header.verhi; if (v1 > 1) { Debug.LogErrorFormat("sff file not supoort v{0:D}.{1:D}.{2:D}.{3:D}", v1, v2, v3, v4); return false; } // MemoryStream stream = new MemoryStream(bytes); try { if (!LoadSubFiles(header, bytes)) return false; // if (!LoadSubFiles(header, stream)) // return false; if (!LoadPcxs(header, bytes)) return false; } finally { // stream.Close(); // stream.Dispose(); } } else { Debug.LogErrorFormat("sff file not supoort v{0:D}", v1); return false; } if (v1 > 1) { Debug.LogErrorFormat("sff file not supoort v{0:D}.{1:D}.{2:D}.{3:D}", v1, v2, v3, v4); return false; } mIsVaild = true; return true; }
internal static void FreeTensorData(IntPtr data, IntPtr len, IntPtr closure) { Marshal.FreeHGlobal(data); }
/// <summary> /// Converts decoded, raw frame data in the frame source into a a usable frame. <br /> /// The process includes performing picture, samples or text conversions /// so that the decoded source frame data is easily usable in multimedia applications /// </summary> /// <param name="input">The source frame to use as an input.</param> /// <param name="output">The target frame that will be updated with the source frame. If null is passed the frame will be instantiated.</param> /// <param name="siblings">The siblings to help guess additional frame parameters.</param> /// <returns> /// Return the updated output frame /// </returns> /// <exception cref="System.ArgumentNullException">input</exception> public override MediaBlock MaterializeFrame(MediaFrame input, ref MediaBlock output, List <MediaBlock> siblings) { if (output == null) { output = new VideoBlock(); } var source = input as VideoFrame; var target = output as VideoBlock; if (source == null || target == null) { throw new ArgumentNullException($"{nameof(input)} and {nameof(output)} are either null or not of a compatible media type '{MediaType}'"); } // Retrieve a suitable scaler or create it on the fly Scaler = ffmpeg.sws_getCachedContext( Scaler, source.Pointer->width, source.Pointer->height, NormalizePixelFormat(source.Pointer), source.Pointer->width, source.Pointer->height, OutputPixelFormat, ScalerFlags, null, null, null); RC.Current.Add(Scaler, $"311: {nameof(VideoComponent)}.{nameof(MaterializeFrame)}()"); // Perform scaling and save the data to our unmanaged buffer pointer var targetBufferStride = ffmpeg.av_image_get_linesize(OutputPixelFormat, source.Pointer->width, 0); var targetStride = new int[] { targetBufferStride }; var targetLength = ffmpeg.av_image_get_buffer_size(OutputPixelFormat, source.Pointer->width, source.Pointer->height, 1); // Ensure proper allocation of the buffer // If there is a size mismatch between the wanted buffer length and the existing one, // then let's reallocate the buffer and set the new size (dispose of the existing one if any) if (target.PictureBufferLength != targetLength) { if (target.PictureBuffer != IntPtr.Zero) { Marshal.FreeHGlobal(target.PictureBuffer); } target.PictureBufferLength = targetLength; target.PictureBuffer = Marshal.AllocHGlobal(target.PictureBufferLength); } var targetScan = default(byte_ptrArray8); targetScan[0] = (byte *)target.PictureBuffer; // The scaling is done here var outputHeight = ffmpeg.sws_scale(Scaler, source.Pointer->data, source.Pointer->linesize, 0, source.Pointer->height, targetScan, targetStride); // Flag the block if we have to target.IsStartTimeGuessed = source.HasValidStartTime == false; // Try to fix the start time, duration and End time if we don't have valid data if (source.HasValidStartTime == false && siblings != null && siblings.Count > 0) { // Get timing information from the last sibling var lastSibling = siblings[siblings.Count - 1]; // We set the target properties target.StartTime = lastSibling.EndTime; target.Duration = source.Duration.Ticks > 0 ? source.Duration : lastSibling.Duration; target.EndTime = TimeSpan.FromTicks(target.StartTime.Ticks + target.Duration.Ticks); } else { // We set the target properties directly from the source target.StartTime = source.StartTime; target.Duration = source.Duration; target.EndTime = source.EndTime; } target.StreamIndex = input.StreamIndex; target.SmtpeTimecode = source.SmtpeTimecode; target.DisplayPictureNumber = source.DisplayPictureNumber; target.CodedPictureNumber = source.DisplayPictureNumber; target.BufferStride = targetStride[0]; target.PixelHeight = source.Pointer->height; target.PixelWidth = source.Pointer->width; var aspectRatio = source.Pointer->sample_aspect_ratio; if (aspectRatio.num == 0 || aspectRatio.den == 0) { target.AspectWidth = 1; target.AspectHeight = 1; } else { target.AspectWidth = aspectRatio.num; target.AspectHeight = aspectRatio.den; } return(target); }
/// <summary> /// Decrypts data that has been encrypted with the <see cref="ProtectData"/> method. /// </summary> /// <param name="data">The data to decrypt.</param> /// <param name="offset">The zero-based position in the <i>data</i> parameter at which to begin decrypting.</param> /// <param name="size">The number of bytes to decrypt.</param> /// <param name="entropy">Additional entropy to use during the decryption process. This parameter can be set to null.</param> /// <exception cref="ArgumentNullException"><i>data</i> is a null reference (<b>Nothing</b> in Visual Basic).</exception> /// <exception cref="ArgumentException">The specified <i>offset</i> or <i>size</i> exceeds the size of buffer.</exception> /// <exception cref="CryptographicException">An error occurs during the encryption process. Under some circumstances, Microsoft cryptographic service providers may not allow encryption when used in France. This may occur on down-level platforms such as Windows 98 and Windows NT 4.0, depending on the system's configuration and the version of the CSPs.</exception> /// <returns>The decrypted data.</returns> /// <remarks>The entropy used during decryption must be the same as the entropy used during encryption.</remarks> public byte[] UnprotectData(byte[] data, int offset, int size, byte[] entropy) { if (m_Disposed) { throw new ObjectDisposedException(this.GetType().FullName); } if (data == null) { throw new ArgumentNullException(); } if (offset < 0 || offset + size > data.Length) { throw new ArgumentException(); } DataBlob input = new DataBlob(); DataBlob entr = new DataBlob(); DataBlob output = new DataBlob(); try { // initialize input structure input.cbData = size; input.pbData = Marshal.AllocHGlobal(size); Marshal.Copy(data, offset, input.pbData, size); // initialize entropy structure if (entropy == null) { entr.cbData = 0; entr.pbData = IntPtr.Zero; } else { entr.cbData = entropy.Length; entr.pbData = Marshal.AllocHGlobal(entr.cbData); Marshal.Copy(entropy, 0, entr.pbData, entr.cbData); } // initialize output structure output.cbData = 0; output.pbData = IntPtr.Zero; // call the function and check for errors int flags = 0; if (!Environment.UserInteractive) { flags = flags | SecurityConstants.CRYPTPROTECT_UI_FORBIDDEN; } if (SspiProvider.CryptUnprotectData(ref input, IntPtr.Zero, ref entr, IntPtr.Zero, IntPtr.Zero, flags, ref output) == 0 || output.pbData == IntPtr.Zero) { throw new CryptographicException("The data could not be unprotected."); } byte[] ret = new byte[output.cbData]; Marshal.Copy(output.pbData, ret, 0, output.cbData); return(ret); } finally { if (input.pbData != IntPtr.Zero) { Marshal.FreeHGlobal(input.pbData); } if (entr.pbData != IntPtr.Zero) { Marshal.FreeHGlobal(entr.pbData); } if (output.pbData != IntPtr.Zero) { Marshal.FreeHGlobal(output.pbData); } } }
internal static void Free(cef_request_handler_t *ptr) { Marshal.FreeHGlobal((IntPtr)ptr); }
/// <summary> /// Calls DPAPI CryptProtectData function to encrypt an array of /// plaintext bytes. /// </summary> /// <param name="keyType"> /// Defines type of encryption key to use. When user key is /// specified, any application running under the same user account /// as the one making this call, will be able to decrypt data. /// Machine key will allow any application running on the same /// computer where data were encrypted to perform decryption. /// Note: If optional entropy is specifed, it will be required /// for decryption. /// </param> /// <param name="plainTextBytes"> /// Plaintext data to be encrypted. /// </param> /// <param name="entropyBytes"> /// Optional entropy which - if specified - will be required to /// perform decryption. /// </param> /// <param name="description"> /// Optional description of data to be encrypted. If this value is /// specified, it will be stored along with encrypted data and /// returned as a separate value during decryption. /// </param> /// <returns> /// Encrypted value. /// </returns> public static byte[] Encrypt(KeyType keyType, byte[] plainTextBytes, byte[] entropyBytes, string description) { // Make sure that parameters are valid. if (plainTextBytes == null) { plainTextBytes = new byte[0]; } if (entropyBytes == null) { entropyBytes = new byte[0]; } if (description == null) { description = String.Empty; } // Create BLOBs to hold data. DATA_BLOB plainTextBlob = new DATA_BLOB(); DATA_BLOB cipherTextBlob = new DATA_BLOB(); DATA_BLOB entropyBlob = new DATA_BLOB(); // We only need prompt structure because it is a required // parameter. CRYPTPROTECT_PROMPTSTRUCT prompt = new CRYPTPROTECT_PROMPTSTRUCT(); InitPrompt(ref prompt); try { // Convert plaintext bytes into a BLOB structure. try { InitBLOB(plainTextBytes, ref plainTextBlob); } catch (Exception ex) { throw new Exception( "Cannot initialize plaintext BLOB.", ex); } // Convert entropy bytes into a BLOB structure. try { InitBLOB(entropyBytes, ref entropyBlob); } catch (Exception ex) { throw new Exception( "Cannot initialize entropy BLOB.", ex); } // Disable any types of UI. int flags = CRYPTPROTECT_UI_FORBIDDEN; // When using machine-specific key, set up machine flag. if (keyType == KeyType.MachineKey) { flags |= CRYPTPROTECT_LOCAL_MACHINE; } // Call DPAPI to encrypt data. bool success = CryptProtectData(ref plainTextBlob, description, ref entropyBlob, IntPtr.Zero, ref prompt, flags, ref cipherTextBlob); // Check the result. if (!success) { // If operation failed, retrieve last Win32 error. int errCode = Marshal.GetLastWin32Error(); // Win32Exception will contain error message corresponding // to the Windows error code. throw new Exception( "CryptProtectData failed.", new Win32Exception(errCode)); } // Allocate memory to hold ciphertext. byte[] cipherTextBytes = new byte[cipherTextBlob.cbData]; // Copy ciphertext from the BLOB to a byte array. Marshal.Copy(cipherTextBlob.pbData, cipherTextBytes, 0, cipherTextBlob.cbData); // Return the result. return(cipherTextBytes); } catch (Exception ex) { throw new Exception("DPAPI was unable to encrypt data.", ex); } // Free all memory allocated for BLOBs. finally { if (plainTextBlob.pbData != IntPtr.Zero) { Marshal.FreeHGlobal(plainTextBlob.pbData); } if (cipherTextBlob.pbData != IntPtr.Zero) { Marshal.FreeHGlobal(cipherTextBlob.pbData); } if (entropyBlob.pbData != IntPtr.Zero) { Marshal.FreeHGlobal(entropyBlob.pbData); } } }
public override void Deserialize(byte[] SERIALIZEDSTUFF, ref int currentIndex) { int arraylength = -1; bool hasmetacomponents = false; object __thing; int piecesize = 0; byte[] thischunk, scratch1, scratch2; IntPtr h; //mode piecesize = Marshal.SizeOf(typeof(int)); h = IntPtr.Zero; if (SERIALIZEDSTUFF.Length - currentIndex != 0) { h = Marshal.AllocHGlobal(piecesize); Marshal.Copy(SERIALIZEDSTUFF, currentIndex, h, piecesize); } if (h == IntPtr.Zero) { throw new Exception("Alloc failed"); } mode = (int)Marshal.PtrToStructure(h, typeof(int)); Marshal.FreeHGlobal(h); currentIndex += piecesize; //command hasmetacomponents |= false; arraylength = BitConverter.ToInt32(SERIALIZEDSTUFF, currentIndex); currentIndex += Marshal.SizeOf(typeof(System.Int32)); if (command == null) { command = new double[arraylength]; } else { Array.Resize(ref command, arraylength); } for (int i = 0; i < command.Length; i++) { //command[i] piecesize = Marshal.SizeOf(typeof(double)); h = IntPtr.Zero; if (SERIALIZEDSTUFF.Length - currentIndex != 0) { h = Marshal.AllocHGlobal(piecesize); Marshal.Copy(SERIALIZEDSTUFF, currentIndex, h, piecesize); } if (h == IntPtr.Zero) { throw new Exception("Alloc failed"); } command[i] = (double)Marshal.PtrToStructure(h, typeof(double)); Marshal.FreeHGlobal(h); currentIndex += piecesize; } //names hasmetacomponents |= false; arraylength = BitConverter.ToInt32(SERIALIZEDSTUFF, currentIndex); currentIndex += Marshal.SizeOf(typeof(System.Int32)); if (names == null) { names = new string[arraylength]; } else { Array.Resize(ref names, arraylength); } for (int i = 0; i < names.Length; i++) { //names[i] names[i] = ""; piecesize = BitConverter.ToInt32(SERIALIZEDSTUFF, currentIndex); currentIndex += 4; names[i] = Encoding.ASCII.GetString(SERIALIZEDSTUFF, currentIndex, piecesize); currentIndex += piecesize; } }
public static string GetVersion() { using (UnmanagedLibrary openGLLib = new UnmanagedLibrary("opengl32.dll")) using (UnmanagedLibrary gdi32Lib = new UnmanagedLibrary("Gdi32.dll")) { IntPtr deviceContextHandle = Imports.GetDC(Process.GetCurrentProcess().MainWindowHandle); if (deviceContextHandle == IntPtr.Zero) { throw new Exception("Failed to get device context from the main window."); } IntPtr choosePixelFormatAddress = Imports.GetProcAddress(gdi32Lib.Handle, "ChoosePixelFormat"); if (choosePixelFormatAddress == IntPtr.Zero) { throw new Exception($"Failed to get ChoosePixelFormat address ({Marshal.GetLastWin32Error()})."); } ChoosePixelFormatDelegate choosePixelFormat = Marshal.GetDelegateForFunctionPointer <ChoosePixelFormatDelegate>(choosePixelFormatAddress); PIXELFORMATDESCRIPTOR pfd = new PIXELFORMATDESCRIPTOR { nSize = (UInt16)Marshal.SizeOf(typeof(PIXELFORMATDESCRIPTOR)), nVersion = 1, dwFlags = (PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER), iPixelType = PFD_TYPE_RGBA, cColorBits = 32, cRedBits = 0, cRedShift = 0, cGreenBits = 0, cGreenShift = 0, cBlueBits = 0, cBlueShift = 0, cAlphaBits = 0, cAlphaShift = 0, cAccumBits = 0, cAccumRedBits = 0, cAccumGreenBits = 0, cAccumBlueBits = 0, cAccumAlphaBits = 0, cDepthBits = 24, cStencilBits = 8, cAuxBuffers = 0, iLayerType = PFD_MAIN_PLANE, bReserved = 0, dwLayerMask = 0, dwVisibleMask = 0, dwDamageMask = 0 }; IntPtr pfdPtr = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(PIXELFORMATDESCRIPTOR))); try { Marshal.StructureToPtr(pfd, pfdPtr, false); int pixelFormat = choosePixelFormat(deviceContextHandle, pfdPtr); if (pixelFormat == 0) { throw new Exception($"Failed to choose pixel format ({Marshal.GetLastWin32Error()})."); } IntPtr setPixelFormatAddress = Imports.GetProcAddress(gdi32Lib.Handle, "SetPixelFormat"); if (setPixelFormatAddress == IntPtr.Zero) { throw new Exception($"Failed to get SetPixelFormat address ({Marshal.GetLastWin32Error()})."); } SetPixelFormatDelegate setPixelFormat = Marshal.GetDelegateForFunctionPointer <SetPixelFormatDelegate>(setPixelFormatAddress); if (setPixelFormat(deviceContextHandle, pixelFormat, pfdPtr) <= 0) { throw new Exception($"Failed to set pixel format ({Marshal.GetLastWin32Error()})."); } IntPtr wglCreateContextAddress = Imports.GetProcAddress(openGLLib.Handle, "wglCreateContext"); if (wglCreateContextAddress == IntPtr.Zero) { throw new Exception($"Failed to get wglCreateContext address ({Marshal.GetLastWin32Error()})."); } wglCreateContextDelegate wglCreateContext = Marshal.GetDelegateForFunctionPointer <wglCreateContextDelegate>(wglCreateContextAddress); IntPtr wglDeleteContextAddress = Imports.GetProcAddress(openGLLib.Handle, "wglDeleteContext"); if (wglDeleteContextAddress == IntPtr.Zero) { throw new Exception($"Failed to get wglDeleteContext address ({Marshal.GetLastWin32Error()})."); } wglDeleteContextDelegate wglDeleteContext = Marshal.GetDelegateForFunctionPointer <wglDeleteContextDelegate>(wglDeleteContextAddress); IntPtr openGLRenderingContext = wglCreateContext(deviceContextHandle); if (openGLRenderingContext == IntPtr.Zero) { throw new Exception($"Failed to create OpenGL rendering context ({Marshal.GetLastWin32Error()})."); } try { IntPtr wglMakeCurrentAddress = Imports.GetProcAddress(openGLLib.Handle, "wglMakeCurrent"); if (wglMakeCurrentAddress == IntPtr.Zero) { throw new Exception($"Failed to get wglMakeCurrent address ({Marshal.GetLastWin32Error()})."); } wglMakeCurrentDelegate wglMakeCurrent = Marshal.GetDelegateForFunctionPointer <wglMakeCurrentDelegate>(wglMakeCurrentAddress); if (wglMakeCurrent(deviceContextHandle, openGLRenderingContext) <= 0) { throw new Exception($"Failed to make current device context ({Marshal.GetLastWin32Error()})."); } IntPtr glGetStringAddress = Imports.GetProcAddress(openGLLib.Handle, "glGetString"); if (glGetStringAddress == IntPtr.Zero) { throw new Exception($"Failed to get glGetString address ({Marshal.GetLastWin32Error()})."); } glGetStringDelegate glGetString = Marshal.GetDelegateForFunctionPointer <glGetStringDelegate>(glGetStringAddress); IntPtr versionStrPtr = glGetString(GL_VERSION); if (versionStrPtr == IntPtr.Zero) { // I don't think this ever goes wrong, in the context of OP's question and considering the current code. throw new Exception("Failed to get OpenGL version string."); } return(Marshal.PtrToStringAnsi(versionStrPtr)); } finally { wglDeleteContext(openGLRenderingContext); } } finally { Marshal.FreeHGlobal(pfdPtr); } } }
public void GetInformation(IMediaImage imagePlugin, Partition partition, out string information, Encoding encoding) { Encoding = encoding ?? Encoding.GetEncoding("iso-8859-15"); information = ""; StringBuilder sb = new StringBuilder(); XmlFsType = new FileSystemType(); byte[] vbrSector = imagePlugin.ReadSector(0 + partition.Start); IntPtr vbrPtr = Marshal.AllocHGlobal(512); Marshal.Copy(vbrSector, 0, vbrPtr, 512); VolumeBootRecord vbr = (VolumeBootRecord)Marshal.PtrToStructure(vbrPtr, typeof(VolumeBootRecord)); Marshal.FreeHGlobal(vbrPtr); byte[] parametersSector = imagePlugin.ReadSector(9 + partition.Start); IntPtr parametersPtr = Marshal.AllocHGlobal(512); Marshal.Copy(parametersSector, 0, parametersPtr, 512); OemParameterTable parametersTable = (OemParameterTable)Marshal.PtrToStructure(parametersPtr, typeof(OemParameterTable)); Marshal.FreeHGlobal(parametersPtr); byte[] chkSector = imagePlugin.ReadSector(11 + partition.Start); IntPtr chkPtr = Marshal.AllocHGlobal(512); Marshal.Copy(chkSector, 0, chkPtr, 512); ChecksumSector chksector = (ChecksumSector)Marshal.PtrToStructure(chkPtr, typeof(ChecksumSector)); Marshal.FreeHGlobal(chkPtr); sb.AppendLine("Microsoft exFAT"); sb.AppendFormat("Partition offset: {0}", vbr.offset).AppendLine(); sb.AppendFormat("Volume has {0} sectors of {1} bytes each for a total of {2} bytes", vbr.sectors, 1 << vbr.sectorShift, vbr.sectors * (ulong)(1 << vbr.sectorShift)).AppendLine(); sb.AppendFormat("Volume uses clusters of {0} sectors ({1} bytes) each", 1 << vbr.clusterShift, (1 << vbr.sectorShift) * (1 << vbr.clusterShift)).AppendLine(); sb.AppendFormat("First FAT starts at sector {0} and runs for {1} sectors", vbr.fatOffset, vbr.fatLength) .AppendLine(); sb.AppendFormat("Volume uses {0} FATs", vbr.fats).AppendLine(); sb.AppendFormat("Cluster heap starts at sector {0}, contains {1} clusters and is {2}% used", vbr.clusterHeapOffset, vbr.clusterHeapLength, vbr.heapUsage).AppendLine(); sb.AppendFormat("Root directory starts at cluster {0}", vbr.rootDirectoryCluster).AppendLine(); sb.AppendFormat("Filesystem revision is {0}.{1:D2}", (vbr.revision & 0xFF00) >> 8, vbr.revision & 0xFF) .AppendLine(); sb.AppendFormat("Volume serial number: {0:X8}", vbr.volumeSerial).AppendLine(); sb.AppendFormat("BIOS drive is {0:X2}h", vbr.drive).AppendLine(); if (vbr.flags.HasFlag(VolumeFlags.SecondFatActive)) { sb.AppendLine("2nd FAT is in use"); } if (vbr.flags.HasFlag(VolumeFlags.VolumeDirty)) { sb.AppendLine("Volume is dirty"); } if (vbr.flags.HasFlag(VolumeFlags.MediaFailure)) { sb.AppendLine("Underlying media presented errors"); } int count = 1; foreach (OemParameter parameter in parametersTable.parameters) { if (parameter.OemParameterType == OEM_FLASH_PARAMETER_GUID) { sb.AppendFormat("OEM Parameters {0}:", count).AppendLine(); sb.AppendFormat("\t{0} bytes in erase block", parameter.eraseBlockSize).AppendLine(); sb.AppendFormat("\t{0} bytes per page", parameter.pageSize).AppendLine(); sb.AppendFormat("\t{0} spare blocks", parameter.spareBlocks).AppendLine(); sb.AppendFormat("\t{0} nanoseconds random access time", parameter.randomAccessTime).AppendLine(); sb.AppendFormat("\t{0} nanoseconds program time", parameter.programTime).AppendLine(); sb.AppendFormat("\t{0} nanoseconds read cycle time", parameter.readCycleTime).AppendLine(); sb.AppendFormat("\t{0} nanoseconds write cycle time", parameter.writeCycleTime).AppendLine(); } else if (parameter.OemParameterType != Guid.Empty) { sb.AppendFormat("Found unknown parameter type {0}", parameter.OemParameterType).AppendLine(); } count++; } sb.AppendFormat("Checksum 0x{0:X8}", chksector.checksum[0]).AppendLine(); XmlFsType.ClusterSize = (1 << vbr.sectorShift) * (1 << vbr.clusterShift); XmlFsType.Clusters = vbr.clusterHeapLength; XmlFsType.Dirty = vbr.flags.HasFlag(VolumeFlags.VolumeDirty); XmlFsType.Type = "exFAT"; XmlFsType.VolumeSerial = $"{vbr.volumeSerial:X8}"; information = sb.ToString(); }
internal static SecurityStatus SafeQueryContextAttribute( SafeContextHandle handle, ContextQueryAttrib attribute, ref byte[] buffer ) { bool gotRef = false; SecurityStatus status = SecurityStatus.InternalError; RuntimeHelpers.PrepareConstrainedRegions(); int pointerSize = System.Environment.Is64BitOperatingSystem ? 8 : 4; //NOTE: update this when 128 bit processors exist IntPtr alloc_buffer = Marshal.AllocHGlobal(sizeof(uint) + pointerSize); //NOTE: this is at most 4 + sizeof(void*) bytes //see struct SecPkgContext_SessionKey // https://msdn.microsoft.com/en-us/library/windows/desktop/aa380096(v=vs.85).aspx try { handle.DangerousAddRef(ref gotRef); } catch (Exception) { if (gotRef) { handle.DangerousRelease(); gotRef = false; buffer = null; } throw; } finally { if (gotRef) { status = ContextNativeMethods.QueryContextAttributes( ref handle.rawHandle, attribute, alloc_buffer ); if (status == SecurityStatus.OK) { KeyStruct key = new KeyStruct(); Marshal.PtrToStructure(alloc_buffer, key); // fit to the proper size, read a byte[] byte[] sizedBuffer = new byte[key.size]; for (int i = 0; i < key.size; i++) { sizedBuffer[i] = Marshal.ReadByte(key.data, i); } buffer = sizedBuffer; } handle.DangerousRelease(); } } Marshal.FreeHGlobal(alloc_buffer); return(status); }
protected override void Disposing() { Marshal.FreeHGlobal(this.colpoints); Marshal.FreeHGlobal(this.depthData); }
public static void FreeMemory(this ImageInfo imageInfo) { Marshal.FreeHGlobal(imageInfo.BufferPtr); }
// The worker method to set all the extension properties for the service private void UpdateServiceConfig(object sender, InstallEventArgs e) { int actionCount = m_failureActions.Count; // Do we need to do any work that the base installer did not do already? if (actionCount == 0) { return; } // We've got work to do IntPtr serviceManagerHandle = IntPtr.Zero; IntPtr serviceHandle = IntPtr.Zero; IntPtr serviceLockHandle = IntPtr.Zero; IntPtr actionsPtr = IntPtr.Zero; IntPtr failureActionsPtr = IntPtr.Zero; // Err check var bool result = false; // Place all our code in a try block try { // Open the service control manager serviceManagerHandle = WindowsApi.OpenSCManager(null, null, SC_MANAGER_ALL_ACCESS); if (serviceManagerHandle.ToInt32() <= 0) { LogInstallMessage(EventLogEntryType.Error, m_logMessagePrefix + "Failed to Open Service Control Manager"); return; } // Lock the Service Database serviceLockHandle = WindowsApi.LockServiceDatabase(serviceManagerHandle); if (serviceLockHandle.ToInt32() <= 0) { LogInstallMessage(EventLogEntryType.Error, m_logMessagePrefix + "Failed to Lock Service Database for Write"); return; } // Open the service serviceHandle = WindowsApi.OpenService(serviceManagerHandle, base.ServiceName, SERVICE_ALL_ACCESS); if (serviceHandle.ToInt32() <= 0) { LogInstallMessage(EventLogEntryType.Information, m_logMessagePrefix + "Failed to Open Service "); return; } // Need to set service failure actions. Note that the API lets us set as many as // we want, yet the Service Control Manager GUI only lets us see the first 3. // Bill is aware of this and has promised no fixes. Also note that the API allows // granularity of seconds whereas GUI only shows days and minutes. // Calculate size of SC_ACTION structure int scActionSize = Marshal.SizeOf(typeof(WindowsApi.SC_ACTION)); bool needShutdownPrivilege = false; // Allocate memory for the array of individual actions actionsPtr = Marshal.AllocHGlobal(scActionSize * actionCount); // Set up the restart actions array by copying in each failure action structure for (int i = 0; i < actionCount; i++) { // Handle pointer math as 64-bit, cast will convert back to 32-bit if needed Marshal.StructureToPtr(m_failureActions[i], (IntPtr)((Int64)actionsPtr + i * scActionSize), false); if (m_failureActions[i].Type == WindowsApi.SC_ACTION_TYPE.SC_ACTION_REBOOT) { needShutdownPrivilege = true; } } // If we need shutdown privilege, then grant it to this process if (needShutdownPrivilege) { result = GrantShutdownPrivilege(); if (!result) { return; } } // Set up the failure actions WindowsApi.SERVICE_FAILURE_ACTIONS failureActions = new WindowsApi.SERVICE_FAILURE_ACTIONS(); failureActions.cActions = actionCount; failureActions.dwResetPeriod = m_failResetPeriod; failureActions.lpCommand = m_failRunCommand; failureActions.lpRebootMsg = m_failRebootMessage; failureActions.lpsaActions = actionsPtr; failureActionsPtr = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(WindowsApi.SERVICE_FAILURE_ACTIONS))); Marshal.StructureToPtr(failureActions, failureActionsPtr, false); // Make the change result = WindowsApi.ChangeServiceConfig2(serviceHandle, SERVICE_CONFIG_FAILURE_ACTIONS, failureActionsPtr); // Check the return if (!result) { int err = WindowsApi.GetLastError(); if (err == WindowsApi.ERROR_ACCESS_DENIED) { throw new Exception(m_logMessagePrefix + "Access Denied while setting service failure actions"); } } LogInstallMessage(EventLogEntryType.Information, m_logMessagePrefix + "Successfully configured service failure actions"); // Failure actions flag only applies on Vista / 2008 or better if (Environment.OSVersion.Platform == PlatformID.Win32NT && Environment.OSVersion.Version.Major >= 6) { WindowsApi.SERVICE_FAILURE_ACTIONS_FLAG failureActionFlag = new WindowsApi.SERVICE_FAILURE_ACTIONS_FLAG(); failureActionFlag.bFailureAction = m_executeActionsOnNonCrashErrors; result = WindowsApi.ChangeServiceConfig2(serviceHandle, SERVICE_CONFIG_FAILURE_ACTIONS_FLAG, ref failureActionFlag); // Error setting description? if (!result) { throw new Exception(m_logMessagePrefix + "Failed to set failure actions flag"); } } } // Catch all exceptions catch (Exception ex) { LogInstallMessage(EventLogEntryType.Error, ex.Message); } finally { if (serviceManagerHandle != IntPtr.Zero) { // Unlock the service database if (serviceLockHandle != IntPtr.Zero) { WindowsApi.UnlockServiceDatabase(serviceLockHandle); } // Close the service control manager handle WindowsApi.CloseServiceHandle(serviceManagerHandle); } // Close the service handle if (serviceHandle != IntPtr.Zero) { WindowsApi.CloseServiceHandle(serviceHandle); } // Free allocated memory if (failureActionsPtr != IntPtr.Zero) { Marshal.FreeHGlobal(failureActionsPtr); } if (actionsPtr != IntPtr.Zero) { Marshal.FreeHGlobal(actionsPtr); } } }
internal GlyphInfo LoadGlyph(char codePoint) { if (!_pages.ContainsKey(codePoint)) { // Load the glyph from the font face Glyph glyph = FontFace.GetGlyph(codePoint, FontSize); if (glyph == null) { if (!_errorChars.Contains(codePoint)) { Engine.Get.Debug.Warning($"Could not load character '{codePoint}' for font '{FontFace.FullName}'"); _errorChars.Add(codePoint); } return(GlyphInfo.Empty); } // Load the glyph into the texture Surface fontSurface = new Surface { Bits = Marshal.AllocHGlobal(glyph.RenderWidth * glyph.RenderHeight), Width = glyph.RenderWidth, Height = glyph.RenderHeight, Pitch = glyph.RenderWidth }; // Clear the memory region of the surface bits Marshal.Copy(new byte[glyph.RenderWidth * glyph.RenderHeight], 0, fontSurface.Bits, glyph.RenderWidth * glyph.RenderHeight); // Render the glyph to the surface glyph.RenderTo(fontSurface); int width = fontSurface.Width; int height = fontSurface.Height; int len = width * height; byte[] data = new byte[len]; // Copy the bits into the data bytes array Marshal.Copy(fontSurface.Bits, data, 0, len); // Free the memory of the surface bits Marshal.FreeHGlobal(fontSurface.Bits); // Create RGBA version of data bytes byte[] pixels = new byte[len * 4]; int index = 0; // Fill the RGBA pixels with the data for (int i = 0; i < len; i++) { byte c = data[i]; pixels[index++] = c; pixels[index++] = c; pixels[index++] = c; pixels[index++] = c; } FaceMetrics faceMetrics = FontFace.GetFaceMetrics(FontSize); // padding between glyphs to avoid bleeding in rotated text const int padding = 3; // While the glyph does not fit on the x-axis, keep resizing the texture in the x-axis while (Texture.Size.X <= (_nextFreeColumnPosition + glyph.RenderWidth + padding + RowOffset)) { int newSizeX = Texture.Size.X * 2; // Check if the glyph does not fit on the row if (newSizeX >= Texture.MaxTextureSize) { AddTextureRow(); // Move row to the next available _nextFreeRowPosition = RowOffset; // Reset the column to the start of the line _nextFreeColumnPosition = RowOffset; } else { // Make the texture wider ResizeTexture(newSizeX, Texture.Size.Y); } } // While the glyph does not fit on the y-axis, keep resizing the texture in the y-axis while (Texture.Size.Y <= (_nextFreeRowPosition + glyph.RenderHeight + padding)) { AddTextureRow(); } // Update texture with the glyph Texture.Update(pixels, new IntRect((int)_nextFreeColumnPosition + RowOffset, (int)_nextFreeRowPosition, glyph.RenderWidth, glyph.RenderHeight)); float sourceX = Math.Max(RowOffset, (_nextFreeColumnPosition + RowOffset) - ((float)padding / 2)); // Create the rect representing the region for this glyph on the updated texture FloatRect sourceRect = new FloatRect(sourceX, _nextFreeRowPosition, glyph.RenderWidth + padding, glyph.RenderHeight); // Move column to next available _nextFreeColumnPosition += glyph.RenderWidth + padding; // Create and add glyph info to the pages GlyphInfo glyphInfo = new GlyphInfo { Advance = glyph.HorizontalMetrics.Advance, BearingX = glyph.HorizontalMetrics.Bearing.X, BearingY = glyph.HorizontalMetrics.Bearing.Y, SourceRect = sourceRect }; _pages.Add(codePoint, glyphInfo); } return(_pages[codePoint]); }
HandleResult OnReceive(IntPtr connId, int length) { // 数据到达了 IntPtr clientPtr = IntPtr.Zero; if (server.GetConnectionExtra(connId, ref clientPtr) == false) { return(HandleResult.Error); } ClientInfo ci = (ClientInfo)Marshal.PtrToStructure(clientPtr, typeof(ClientInfo)); PkgInfo pkgInfo = ci.PkgInfo; // 需要长度 int required = pkgInfo.Length; // 剩余大小 int remain = length; while (remain >= required) { IntPtr bufferPtr = IntPtr.Zero; try { remain -= required; bufferPtr = Marshal.AllocHGlobal(required);; if (server.Fetch(connId, bufferPtr, required) == FetchResult.Ok) { if (pkgInfo.IsHeader == true) { PkgHeader header = (PkgHeader)Marshal.PtrToStructure(bufferPtr, typeof(PkgHeader)); // 调试信息 Console.WriteLine("[Server] head -> Id: {0}, BodySize: {1}\r\n", header.Id, header.BodySize); required = header.BodySize; } else { // 调试信息 string recvString = Marshal.PtrToStringAnsi(bufferPtr, required); Console.WriteLine("[Server] body -> text: {0}\r\n", recvString); // intptr转string //Marshal.PtrToStringAnsi(bufferPtr, required); //intptr转byte[] // byte[] bytes = new byte[required]; // Marshal.Copy(bufferPtr, bytes, 0, required); required = pkgHeaderSize; } AddMsg(string.Format(" > [{0},OnReceive] -> ({1} bytes)", connId, pkgInfo.Length)); // 回发数据 byte[] sendBytes = new byte[pkgInfo.Length]; Marshal.Copy(bufferPtr, sendBytes, 0, sendBytes.Length); if (server.Send(connId, sendBytes, sendBytes.Length) == false) { throw new Exception("server.Send() == false"); } // 在后面赋值,因为前面需要用到pkgInfo.Length pkgInfo.IsHeader = !pkgInfo.IsHeader; pkgInfo.Length = required; if (server.SetConnectionExtra(connId, ci) == false) { return(HandleResult.Error); } } } catch { return(HandleResult.Error); } finally { if (bufferPtr != IntPtr.Zero) { Marshal.FreeHGlobal(bufferPtr); bufferPtr = IntPtr.Zero; } } } return(HandleResult.Ok); }