protected override void WndProc(ref Message m) { // When the bars are first loaded, they will always have // RBBS_BREAK set. Catch RB_SETBANDINFO to fix this. if (m.Msg == RB.SETBANDINFO) { if (monitorSetInfo) { REBARBANDINFO pInfo = (REBARBANDINFO)Marshal.PtrToStructure(m.LParam, typeof(REBARBANDINFO)); if (pInfo.hwndChild == parent.Handle && (pInfo.fMask & RBBIM.STYLE) != 0) { // Ask the bar if we actually want a break. if (parent.ShouldHaveBreak()) { pInfo.fStyle |= RBBS.BREAK; } else { pInfo.fStyle &= ~RBBS.BREAK; } Marshal.StructureToPtr(pInfo, m.LParam, false); pInfo = (REBARBANDINFO)Marshal.PtrToStructure(m.LParam, typeof(REBARBANDINFO)); } } } // Whenever a band is deleted, it the RBBS_BREAKs come back! // Catch RB_DELETEBAND to fix it. else if (m.Msg == RB.DELETEBAND) { int del = (int)m.WParam; // Look for our band int n = parent.ActiveRebarCount(); for (int i = 0; i < n; ++i) { REBARBANDINFO info = parent.GetRebarBand(i, RBBIM.STYLE | RBBIM.CHILD); if (info.hwndChild == parent.Handle) { // Call the WndProc to let the deletion fall // through, with the break status safely saved // in the info variable. base.WndProc(ref m); // If *we're* the one being deleted, no need to do // anything else. if (i == del) { return; } // Otherwise, our style has been messed with. // Set it back to what it was. info.cbSize = Marshal.SizeOf(info); info.fMask = RBBIM.STYLE; IntPtr ptr = Marshal.AllocHGlobal(Marshal.SizeOf(info)); Marshal.StructureToPtr(info, ptr, false); bool reset = monitorSetInfo; monitorSetInfo = false; SendMessage(parent.ReBarHandle, RB.SETBANDINFO, (IntPtr)i, ptr); monitorSetInfo = reset; Marshal.FreeHGlobal(ptr); // Return without calling WndProc twice! return; } } } base.WndProc(ref m); }
public bool InitSession(bool screen, string url) { if (pls_client_ != IntPtr.Zero) { ClearSession(); } string path = NIM.ToolsAPI.GetLocalAppDataDir() + @"NIMCSharpDemo\NIM\NIM_LS"; IntPtr ptr = new IntPtr(); int ls_ret = LSClientNativeMethods.Nlss_Create(path, out ptr); System.Diagnostics.Debug.Assert(ls_ret == 0); ls_para_.stAudioParam.enInType = enum_NLSS_AUDIOIN_TYPE.EN_NLSS_AUDIOIN_RAWDATA; ls_para_.stVideoParam.enInType = enum_NLSS_VIDEOIN_TYPE.EN_NLSS_VIDEOIN_RAWDATA; pls_client_ = new IntPtr(ptr.ToInt64()); int nSizeOfParam = Marshal.SizeOf(ls_para_); IntPtr ptr_ls = Marshal.AllocHGlobal(nSizeOfParam); int ls_ret_default = -1; try { Marshal.StructureToPtr(ls_para_, ptr_ls, false); ls_ret_default = LSClientNativeMethods.Nlss_GetDefaultParam(pls_client_, ptr_ls); ls_para_ = (struct_NLSS_PARAM)Marshal.PtrToStructure(ptr_ls, typeof(struct_NLSS_PARAM)); } catch (Exception ex) { } finally { Marshal.FreeHGlobal(ptr_ls); } System.Diagnostics.Debug.Assert(ls_ret_default == 0); ls_para_.paOutUrl = url; //音频 ls_para_.stAudioParam.iInSamplerate = 44100; ls_para_.stAudioParam.iInnumOfChannels = 1; ls_para_.stAudioParam.iInBitsPerSample = 16; ls_para_.stAudioParam.enInFmt = enum_NLSS_AUDIOIN_FMT.EN_NLSS_AUDIOIN_FMT_S16; //视频 if (width_ == 1280) { //width_ = 1280; //height_ = 720; ls_para_.stVideoParam.iOutBitrate = 1500000; } else { //width_ = 640; //height_ = 480; ls_para_.stVideoParam.iOutBitrate = 700000; } ls_para_.stVideoParam.stInCustomVideo.enVideoInFmt = enum_NLSS_VIDEOIN_FMT.EN_NLSS_VIDEOIN_FMT_I420; ls_para_.stVideoParam.stInCustomVideo.iInWidth = width_; ls_para_.stVideoParam.stInCustomVideo.iInHeight = height_; ls_para_.stVideoParam.stInCustomVideo.iYStride = width_; ls_para_.stVideoParam.stInCustomVideo.iUVStride = width_ / 2; int nSizeOfParam2 = Marshal.SizeOf(ls_para_); IntPtr ptr_ls2 = Marshal.AllocHGlobal(nSizeOfParam2); try { Marshal.StructureToPtr(ls_para_, ptr_ls2, false); struct_NLSS_PARAM param = (struct_NLSS_PARAM)Marshal.PtrToStructure(ptr_ls2, typeof(struct_NLSS_PARAM)); int ls_ret_init = LSClientNativeMethods.Nlss_InitParam(pls_client_, ptr_ls2); System.Diagnostics.Debug.Assert(ls_ret_init == 0); } catch (Exception ex) { } finally { Marshal.FreeHGlobal(ptr_ls2); } nimSDKHelper.Init(); return(true); }
private IntPtr AllocateSegment() { this.NoisyLog("Allocating segment of size {0}.", SegmentSize); return(Marshal.AllocHGlobal(SegmentSize + Alignment)); }
public static DeviceInfo[] GetInterfaces() { var list = new List <DeviceInfo>(); Guid hidGuid = Guid.Empty; NativeMethods.HidD_GetHidGuid(ref hidGuid); int requiredSize3 = 0; var interfaceData = new SP_DEVICE_INTERFACE_DATA(); interfaceData.Initialize(); List <string> serials = new List <string>(); var deviceInfoSet = NativeMethods.SetupDiGetClassDevs(hidGuid, IntPtr.Zero, IntPtr.Zero, DIGCF.DIGCF_DEVICEINTERFACE); for (int i2 = 0; NativeMethods.SetupDiEnumDeviceInterfaces(deviceInfoSet, IntPtr.Zero, ref hidGuid, i2, ref interfaceData); i2++) { var deviceInfoData = new SP_DEVINFO_DATA(); deviceInfoData.Initialize(); bool success = NativeMethods.SetupDiGetDeviceInterfaceDetail(deviceInfoSet, ref interfaceData, IntPtr.Zero, 0, ref requiredSize3, IntPtr.Zero); IntPtr ptrDetails = Marshal.AllocHGlobal(requiredSize3); Marshal.WriteInt32(ptrDetails, (IntPtr.Size == 4) ? (4 + Marshal.SystemDefaultCharSize) : 8); success = NativeMethods.SetupDiGetDeviceInterfaceDetail(deviceInfoSet, ref interfaceData, ptrDetails, requiredSize3, ref requiredSize3, ref deviceInfoData); var interfaceDetail = (SP_DEVICE_INTERFACE_DETAIL_DATA)Marshal.PtrToStructure(ptrDetails, typeof(SP_DEVICE_INTERFACE_DETAIL_DATA)); var di = GetDeviceInfo(deviceInfoSet, deviceInfoData); di.DevicePath = interfaceDetail.DevicePath; var deviceHandle = deviceInfoData.DevInst; Marshal.FreeHGlobal(ptrDetails); // Open the device as a file so that we can query it with HID and read/write to it. var devHandle = NativeMethods.CreateFile( interfaceDetail.DevicePath, 0, FileShare.ReadWrite, IntPtr.Zero, FileMode.Open, 0, //WinNT.Overlapped IntPtr.Zero ); if (devHandle.IsInvalid) { continue; } var ha = new HIDD_ATTRIBUTES(); ha.Size = Marshal.SizeOf(ha); var success2 = NativeMethods.HidD_GetAttributes(devHandle, ref ha); string serial = ""; string phdesc = ""; if (success2) { IntPtr preparsedDataPtr = new IntPtr(); HIDP_CAPS caps = new HIDP_CAPS(); // Read out the 'pre-parsed data'. NativeMethods.HidD_GetPreparsedData(devHandle, ref preparsedDataPtr); // feed that to GetCaps. NativeMethods.HidP_GetCaps(preparsedDataPtr, ref caps); // Free the 'pre-parsed data'. NativeMethods.HidD_FreePreparsedData(ref preparsedDataPtr); // This could fail if the device was recently attached. // Maximum string length is 126 wide characters (2 bytes each) (not including the terminating NULL character). ulong capacity = (uint)(126 * Marshal.SystemDefaultCharSize + 2); var sb = new StringBuilder((int)capacity, (int)capacity); // Override manufacturer if found. if (NativeMethods.HidD_GetManufacturerString(devHandle, sb, sb.Capacity) && sb.Length > 0) { di.Manufacturer = sb.ToString(); } // Override ProductName if Found. if (NativeMethods.HidD_GetProductString(devHandle, sb, sb.Capacity) && sb.Length > 0) { di.Description = sb.ToString(); } serial = NativeMethods.HidD_GetSerialNumberString(devHandle, sb, sb.Capacity) ? sb.ToString() : ""; phdesc = NativeMethods.HidD_GetPhysicalDescriptor(devHandle, sb, sb.Capacity) ? sb.ToString() : ""; } uint parentDeviceInstance = 0; string parentDeviceId = null; var CRResult = NativeMethods.CM_Get_Parent(out parentDeviceInstance, deviceHandle, 0); if (CRResult == CR.CR_SUCCESS) { parentDeviceId = GetDeviceId(parentDeviceInstance); } list.Add(di); serials.Add(phdesc); devHandle.Close(); } NativeMethods.SetupDiDestroyDeviceInfoList(deviceInfoSet); deviceInfoSet = IntPtr.Zero; return(list.ToArray()); }
public byte[] Encrypt(byte[] plainText, byte[] optionalEntropy) { bool retVal = false; DATA_BLOB plainTextBlob = new DATA_BLOB(); DATA_BLOB cipherTextBlob = new DATA_BLOB(); DATA_BLOB entropyBlob = new DATA_BLOB(); CRYPTPROTECT_PROMPTSTRUCT prompt = new CRYPTPROTECT_PROMPTSTRUCT(); InitPromptstruct(ref prompt); int dwFlags; try { try { int bytesSize = plainText.Length; plainTextBlob.pbData = Marshal.AllocHGlobal(bytesSize); if (IntPtr.Zero == plainTextBlob.pbData) { throw new Exception("Unable to allocate plaintext buffer."); } plainTextBlob.cbData = bytesSize; Marshal.Copy(plainText, 0, plainTextBlob.pbData, bytesSize); } catch (Exception ex) { throw new Exception("Exception marshalling data. " + ex.Message); } if (Store.USE_MACHINE_STORE == store) { //Using the machine store, should be providing entropy. dwFlags = CRYPTPROTECT_LOCAL_MACHINE | CRYPTPROTECT_UI_FORBIDDEN; //Check to see if the entropy is null if (null == optionalEntropy) { //Allocate something optionalEntropy = new byte[0]; } try { int bytesSize = optionalEntropy.Length; entropyBlob.pbData = Marshal.AllocHGlobal(optionalEntropy.Length);; if (IntPtr.Zero == entropyBlob.pbData) { throw new Exception("Unable to allocate entropy data buffer."); } Marshal.Copy(optionalEntropy, 0, entropyBlob.pbData, bytesSize); entropyBlob.cbData = bytesSize; } catch (Exception ex) { throw new Exception("Exception entropy marshalling data. " + ex.Message); } } else { //Using the user store dwFlags = CRYPTPROTECT_UI_FORBIDDEN; } retVal = CryptProtectData(ref plainTextBlob, "", ref entropyBlob, IntPtr.Zero, ref prompt, dwFlags, ref cipherTextBlob); if (false == retVal) { throw new Exception("Encryption failed. " + GetErrorMessage(Marshal.GetLastWin32Error())); } //Free the blob and entropy. if (IntPtr.Zero != plainTextBlob.pbData) { Marshal.FreeHGlobal(plainTextBlob.pbData); } if (IntPtr.Zero != entropyBlob.pbData) { Marshal.FreeHGlobal(entropyBlob.pbData); } } catch (Exception ex) { throw new Exception("Exception encrypting. " + ex.Message); } byte[] cipherText = new byte[cipherTextBlob.cbData]; Marshal.Copy(cipherTextBlob.pbData, cipherText, 0, cipherTextBlob.cbData); Marshal.FreeHGlobal(cipherTextBlob.pbData); return(cipherText); }
protected virtual IntPtr Allocate() { return(Marshal.AllocHGlobal(Marshal.SizeOf(this.obj))); }
public static Dictionary <string, string> GetCurrentPowerEnumerateVistaAPI() { Dictionary <string, string> powerDictionary = new Dictionary <string, string>(); IntPtr activeGuidPtr = IntPtr.Zero; try { uint res = PowerGetActiveScheme(IntPtr.Zero, ref activeGuidPtr); if (res != 0) { throw new Win32Exception(); } //Get Friendly Name uint buffSize = 0; StringBuilder buffer = new StringBuilder(); Guid subGroupGuid = Guid.Empty; Guid powerSettingGuid = Guid.Empty; res = PowerReadFriendlyName(IntPtr.Zero, activeGuidPtr, IntPtr.Zero, IntPtr.Zero, buffer, ref buffSize); if (res == ERROR_MORE_DATA) { buffer.Capacity = (int)buffSize; res = PowerReadFriendlyName(IntPtr.Zero, activeGuidPtr, IntPtr.Zero, IntPtr.Zero, buffer, ref buffSize); } if (res != 0) { throw new Win32Exception(); } Console.WriteLine("PowerProfileName = " + buffer.ToString()); powerDictionary.Add("PowerProfileName", buffer.ToString()); //Get the Power Settings Guid VideoSettingGuid = Guid.Empty; uint index = 0; uint BufferSize = Convert.ToUInt32(Marshal.SizeOf(typeof(Guid))); while ( PowerEnumerate(IntPtr.Zero, activeGuidPtr, ref GUID_VIDEO_SUBGROUP, 18, index, ref VideoSettingGuid, ref BufferSize) == 0) { uint size = 4; IntPtr temp = IntPtr.Zero; int type = 0; res = PowerReadACValue(IntPtr.Zero, activeGuidPtr, IntPtr.Zero, ref VideoSettingGuid, ref type, ref temp, ref size); IntPtr pSubGroup = Marshal.AllocHGlobal(Marshal.SizeOf(GUID_VIDEO_SUBGROUP)); Marshal.StructureToPtr(GUID_VIDEO_SUBGROUP, pSubGroup, false); IntPtr pSetting = Marshal.AllocHGlobal(Marshal.SizeOf(VideoSettingGuid)); Marshal.StructureToPtr(VideoSettingGuid, pSetting, false); uint builderSize = 200; StringBuilder builder = new StringBuilder((int)builderSize); res = PowerReadFriendlyName(IntPtr.Zero, activeGuidPtr, pSubGroup, pSetting, builder, ref builderSize); Console.WriteLine(builder.ToString() + " = " + temp.ToString()); powerDictionary.Add(builder.ToString().Replace(" ", "_"), temp.ToString()); index++; } } finally { if (activeGuidPtr != IntPtr.Zero) { IntPtr res = LocalFree(activeGuidPtr); if (res != IntPtr.Zero) { throw new Win32Exception(); } } } return(powerDictionary); }
public static void StartPacketReaderMMF() { int nodeBufferSize = sizeof(byte) * _pktMmfBufferSize; SharedMemory.CircularBuffer packetMMF; if (!CheckMMFileExists(_pktMmfName)) { packetMMF = new SharedMemory.CircularBuffer(_pktMmfName, _pktMmfNodeCount, nodeBufferSize); } else { packetMMF = new SharedMemory.CircularBuffer(_pktMmfName); } byte[] writtenData = new byte[_pktMmfBufferSize]; //int threadCount = 0; Action reader = () => { //int myThreadIndex = Interlocked.Increment(ref threadCount); //Output.outMsgBox("Started thread {0}: ", threadCount); for (; ;) { //var t1 = Environment.TickCount; Debug.WriteLine("packetMMF.Read(writtenData) {0}", ID); //var t2 = Environment.TickCount; if (t2-t1 > 0) Debug.WriteLine("ANTES de packetMMF.Read {0} - diff: {1}", ID, t2-t1); //The number of milliseconds to wait, or Timeout.Infinite (-1) to wait indefinitely. int amount = packetMMF.Read(writtenData, 0, -1); //var t3 = Environment.TickCount; if (t3 - t2 > 0) Debug.WriteLine("DESPUES de server.Read {0} - diff: {1}", ID, t3 - t2); if (amount == 0) { throw new Exception("Read 0 bytes from queue!"); } Output.outString("Read data: {0}", BitConverter.ToString(writtenData)); // PacketInfo HEADER var packetInfo = new PacketInfo(); var piSize = Marshal.SizeOf(packetInfo); var piData = new byte[piSize]; // Reads the piSize bytes corresponding to the packetInfo Buffer.BlockCopy(writtenData, 0, piData, 0, piSize); // Converts the bytes to a packetInfo IntPtr ptr = Marshal.AllocHGlobal(piSize); Marshal.Copy(piData, 0, ptr, piSize); packetInfo = (PacketInfo)Marshal.PtrToStructure(ptr, packetInfo.GetType()); var cSize = packetInfo.Size; var cData = new byte[cSize]; // Packet size can not be bigger than buffer size Debug.Assert(cSize < _pktMmfBufferSize); Buffer.BlockCopy(writtenData, piSize, cData, 0, cSize); PacketManager.PacketReceived(packetInfo, ref cData); //var t4 = Environment.TickCount; if (t4- t3 > 0) Debug.WriteLine("DESPUES de PacketManager.PacketReceived {0} - diff: {1}", ID, t4 - t3); } }; // Start reader thread ThreadPool.QueueUserWorkItem(o => { reader(); }); }
public XmlOutputBuffer() { __Instance = Marshal.AllocHGlobal(sizeof(global::libxml.XmlOutputBuffer.__Internal)); __ownsNativeInstance = true; NativeToManagedMap[__Instance] = this; }
public GBHawk(CoreComm comm, GameInfo game, byte[] rom, /*string gameDbFn,*/ GBSettings settings, GBSyncSettings syncSettings) { var ser = new BasicServiceProvider(this); cpu = new LR35902 { ReadMemory = ReadMemory, WriteMemory = WriteMemory, PeekMemory = PeekMemory, DummyReadMemory = ReadMemory, OnExecFetch = ExecFetch, SpeedFunc = SpeedFunc, GetButtons = GetButtons, GetIntRegs = GetIntRegs, SetIntRegs = SetIntRegs }; timer = new Timer(); audio = new Audio(); serialport = new SerialPort(); _settings = (GBSettings)settings ?? new GBSettings(); _syncSettings = (GBSyncSettings)syncSettings ?? new GBSyncSettings(); byte[] Bios = null; // Load up a BIOS and initialize the correct PPU if (_syncSettings.ConsoleMode == GBSyncSettings.ConsoleModeType.Auto) { if (game.System == "GB") { Bios = comm.CoreFileProvider.GetFirmware("GB", "World", true, "BIOS Not Found, Cannot Load"); ppu = new GB_PPU(); } else { Bios = comm.CoreFileProvider.GetFirmware("GBC", "World", true, "BIOS Not Found, Cannot Load"); ppu = new GBC_PPU(); is_GBC = true; } } else if (_syncSettings.ConsoleMode == GBSyncSettings.ConsoleModeType.GB) { Bios = comm.CoreFileProvider.GetFirmware("GB", "World", true, "BIOS Not Found, Cannot Load"); ppu = new GB_PPU(); } else { Bios = comm.CoreFileProvider.GetFirmware("GBC", "World", true, "BIOS Not Found, Cannot Load"); ppu = new GBC_PPU(); is_GBC = true; } if (Bios == null) { throw new MissingFirmwareException("Missing Gamboy Bios"); } _bios = Bios; // set up IR register to off state if (is_GBC) { IR_mask = 0; IR_reg = 0x3E; IR_receive = 2; IR_self = 2; IR_signal = 2; } // Here we modify the BIOS if GBA mode is set (credit to ExtraTricky) if (is_GBC && _syncSettings.GBACGB) { for (int i = 0; i < 13; i++) { _bios[i + 0xF3] = (byte)((GBA_override[i] + _bios[i + 0xF3]) & 0xFF); } IR_mask = 2; } // CPU needs to know about GBC status too cpu.is_GBC = is_GBC; Buffer.BlockCopy(rom, 0x100, header, 0, 0x50); if (is_GBC && ((header[0x43] != 0x80) && (header[0x43] != 0xC0))) { ppu = new GBC_GB_PPU(); } Console.WriteLine("MD5: " + rom.HashMD5(0, rom.Length)); Console.WriteLine("SHA1: " + rom.HashSHA1(0, rom.Length)); _rom = rom; string mppr = Setup_Mapper(); if (cart_RAM != null) { cart_RAM_vbls = new byte[cart_RAM.Length]; } if (mppr == "MBC7") { _controllerDeck = new GBHawkControllerDeck(_syncSettings.Port1); } else { _controllerDeck = new GBHawkControllerDeck(GBHawkControllerDeck.DefaultControllerName); } timer.Core = this; audio.Core = this; ppu.Core = this; serialport.Core = this; ser.Register <IVideoProvider>(this); ser.Register <ISoundProvider>(audio); ServiceProvider = ser; _settings = (GBSettings)settings ?? new GBSettings(); _syncSettings = (GBSyncSettings)syncSettings ?? new GBSyncSettings(); _tracer = new TraceBuffer { Header = cpu.TraceHeader }; ser.Register <ITraceable>(_tracer); ser.Register <IStatable>(new StateSerializer(SyncState)); SetupMemoryDomains(); cpu.SetCallbacks(ReadMemory, PeekMemory, PeekMemory, WriteMemory); HardReset(); iptr0 = Marshal.AllocHGlobal(VRAM.Length + 1); iptr1 = Marshal.AllocHGlobal(OAM.Length + 1); iptr2 = Marshal.AllocHGlobal(ppu.color_palette.Length * 8 * 8 + 1); iptr3 = Marshal.AllocHGlobal(ppu.color_palette.Length * 8 * 8 + 1); _scanlineCallback = null; for (int i = 0; i < ZP_RAM.Length; i++) { ZP_RAM[i] = 0; } if (is_GBC) { if (_syncSettings.GBACGB) { // on GBA, initial RAM is mostly random, choosing 0 allows for stable clear and hotswap for games that encounter // uninitialized RAM for (int i = 0; i < RAM.Length; i++) { RAM[i] = 0; } } else { for (int i = 0; i < 0x800; i++) { if ((i & 0xF) < 8) { RAM[i] = 0xFF; RAM[i + 0x1000] = 0xFF; RAM[i + 0x2000] = 0xFF; RAM[i + 0x3000] = 0xFF; RAM[i + 0x4000] = 0xFF; RAM[i + 0x5000] = 0xFF; RAM[i + 0x6000] = 0xFF; RAM[i + 0x7000] = 0xFF; RAM[i + 0x800] = 0; RAM[i + 0x1800] = 0; RAM[i + 0x2800] = 0; RAM[i + 0x3800] = 0; RAM[i + 0x4800] = 0; RAM[i + 0x5800] = 0; RAM[i + 0x6800] = 0; RAM[i + 0x7800] = 0; } else { RAM[i] = 0; RAM[i + 0x1000] = 0; RAM[i + 0x2000] = 0; RAM[i + 0x3000] = 0; RAM[i + 0x4000] = 0; RAM[i + 0x5000] = 0; RAM[i + 0x6000] = 0; RAM[i + 0x7000] = 0; RAM[i + 0x800] = 0xFF; RAM[i + 0x1800] = 0xFF; RAM[i + 0x2800] = 0xFF; RAM[i + 0x3800] = 0xFF; RAM[i + 0x4800] = 0xFF; RAM[i + 0x5800] = 0xFF; RAM[i + 0x6800] = 0xFF; RAM[i + 0x7800] = 0xFF; } } // some bytes are like this is Gambatte, hardware anomoly? Is it consistent across versions? /* * for (int i = 0; i < 16; i++) * { * RAM[0xE02 + (16 * i)] = 0; * RAM[0xE0A + (16 * i)] = 0xFF; * * RAM[0x1E02 + (16 * i)] = 0; * RAM[0x1E0A + (16 * i)] = 0xFF; * * RAM[0x2E02 + (16 * i)] = 0; * RAM[0x2E0A + (16 * i)] = 0xFF; * * RAM[0x3E02 + (16 * i)] = 0; * RAM[0x3E0A + (16 * i)] = 0xFF; * * RAM[0x4E02 + (16 * i)] = 0; * RAM[0x4E0A + (16 * i)] = 0xFF; * * RAM[0x5E02 + (16 * i)] = 0; * RAM[0x5E0A + (16 * i)] = 0xFF; * * RAM[0x6E02 + (16 * i)] = 0; * RAM[0x6E0A + (16 * i)] = 0xFF; * * RAM[0x7E02 + (16 * i)] = 0; * RAM[0x7E0A + (16 * i)] = 0xFF; * } */ } } else { for (int j = 0; j < 2; j++) { for (int i = 0; i < 0x100; i++) { RAM[j * 0x1000 + i] = 0; RAM[j * 0x1000 + i + 0x100] = 0xFF; RAM[j * 0x1000 + i + 0x200] = 0; RAM[j * 0x1000 + i + 0x300] = 0xFF; RAM[j * 0x1000 + i + 0x400] = 0; RAM[j * 0x1000 + i + 0x500] = 0xFF; RAM[j * 0x1000 + i + 0x600] = 0; RAM[j * 0x1000 + i + 0x700] = 0xFF; RAM[j * 0x1000 + i + 0x800] = 0; RAM[j * 0x1000 + i + 0x900] = 0xFF; RAM[j * 0x1000 + i + 0xA00] = 0; RAM[j * 0x1000 + i + 0xB00] = 0xFF; RAM[j * 0x1000 + i + 0xC00] = 0; RAM[j * 0x1000 + i + 0xD00] = 0xFF; RAM[j * 0x1000 + i + 0xE00] = 0; RAM[j * 0x1000 + i + 0xF00] = 0xFF; } } } }
public SafeMemoryBuffer(int cb) : base(true) { base.SetHandle(Marshal.AllocHGlobal(cb)); }
/// <summary> /// Create an InputArray from a double value /// </summary> /// <param name="scalar">The double value to be converted to InputArray</param> public ScalarArray(double scalar) { _ptr = Marshal.AllocHGlobal(sizeof(double)); _dataType = DataType.Double; Marshal.Copy(new double[] { scalar }, 0, _ptr, 1); }
private void ReadFrames() { var pConvertedFrameBuffer = IntPtr.Zero; SwsContext *pConvertContext = null; var audioInited = false; var videoInited = false; byte[] buffer = null, tbuffer = null; var dstData = new byte_ptrArray4(); var dstLinesize = new int_array4(); BufferedWaveProvider waveProvider = null; SampleChannel sampleChannel = null; var packet = new AVPacket(); do { ffmpeg.av_init_packet(&packet); if (_audioCodecContext != null && buffer == null) { buffer = new byte[_audioCodecContext->sample_rate * 2]; tbuffer = new byte[_audioCodecContext->sample_rate * 2]; } if (Log("AV_READ_FRAME", ffmpeg.av_read_frame(_formatContext, &packet))) { break; } if ((packet.flags & ffmpeg.AV_PKT_FLAG_CORRUPT) == ffmpeg.AV_PKT_FLAG_CORRUPT) { break; } var nf = NewFrame; var da = DataAvailable; _lastPacket = DateTime.UtcNow; int ret; if (_audioStream != null && packet.stream_index == _audioStream->index && _audioCodecContext != null) { if (HasAudioStream != null) { HasAudioStream?.Invoke(this, EventArgs.Empty); HasAudioStream = null; } if (da != null) { var s = 0; fixed(byte **outPtrs = new byte *[32]) { fixed(byte *bPtr = &tbuffer[0]) { outPtrs[0] = bPtr; ffmpeg.avcodec_send_packet(_audioCodecContext, &packet); do { ret = ffmpeg.avcodec_receive_frame(_audioCodecContext, _audioFrame); if (ret == 0) { fixed(byte **datptr = _audioFrame->data.ToArray()) { var numSamplesOut = ffmpeg.swr_convert(_swrContext, outPtrs, _audioCodecContext->sample_rate, datptr, _audioFrame->nb_samples); var l = numSamplesOut * 2 * OutFormat.Channels; Buffer.BlockCopy(tbuffer, 0, buffer, s, l); s += l; } } if (_audioFrame->decode_error_flags > 0) { break; } } while (ret == 0); if (s > 0) { var ba = new byte[s]; Buffer.BlockCopy(buffer, 0, ba, 0, s); if (!audioInited) { audioInited = true; RecordingFormat = new WaveFormat(_audioCodecContext->sample_rate, 16, _audioCodecContext->channels); waveProvider = new BufferedWaveProvider(RecordingFormat) { DiscardOnBufferOverflow = true, BufferDuration = TimeSpan.FromMilliseconds(200) }; sampleChannel = new SampleChannel(waveProvider); sampleChannel.PreVolumeMeter += SampleChannelPreVolumeMeter; } waveProvider.AddSamples(ba, 0, s); var sampleBuffer = new float[s]; var read = sampleChannel.Read(sampleBuffer, 0, s); da(this, new DataAvailableEventArgs(ba, s)); if (Listening) { WaveOutProvider?.AddSamples(ba, 0, read); } } } } } } if (nf != null && _videoStream != null && packet.stream_index == _videoStream->index && _videoCodecContext != null) { ffmpeg.avcodec_send_packet(_videoCodecContext, &packet); do { ret = ffmpeg.avcodec_receive_frame(_videoCodecContext, _videoFrame); var ef = EmitFrame; //Debug.WriteLine("ret: "+ret+", ef:"+ef); if (ret == 0 && ef) { if (!videoInited) { videoInited = true; var convertedFrameBufferSize = ffmpeg.av_image_get_buffer_size(AVPixelFormat.AV_PIX_FMT_BGR24, _videoCodecContext->width, _videoCodecContext->height, 1); pConvertedFrameBuffer = Marshal.AllocHGlobal(convertedFrameBufferSize); ffmpeg.av_image_fill_arrays(ref dstData, ref dstLinesize, (byte *)pConvertedFrameBuffer, AVPixelFormat.AV_PIX_FMT_BGR24, _videoCodecContext->width, _videoCodecContext->height, 1); pConvertContext = ffmpeg.sws_getContext(_videoCodecContext->width, _videoCodecContext->height, _videoCodecContext->pix_fmt, _videoCodecContext->width, _videoCodecContext->height, AVPixelFormat.AV_PIX_FMT_BGR24, ffmpeg.SWS_FAST_BILINEAR, null, null, null); } Log("SWS_SCALE", ffmpeg.sws_scale(pConvertContext, _videoFrame->data, _videoFrame->linesize, 0, _videoCodecContext->height, dstData, dstLinesize)); if (_videoFrame->decode_error_flags > 0) { break; } using ( var mat = new Bitmap(_videoCodecContext->width, _videoCodecContext->height, dstLinesize[0], PixelFormat.Format24bppRgb, pConvertedFrameBuffer)) { var nfe = new NewFrameEventArgs(mat); nf.Invoke(this, nfe); } _lastVideoFrame = DateTime.UtcNow; } } while (ret == 0); } if (nf != null && _videoStream != null) { if ((DateTime.UtcNow - _lastVideoFrame).TotalMilliseconds > _timeout) { _res = ReasonToFinishPlaying.DeviceLost; _abort = true; } } ffmpeg.av_packet_unref(&packet); } while (!_abort && !MainForm.ShuttingDown); NewFrame?.Invoke(this, new NewFrameEventArgs(null)); try { Program.MutexHelper.Wait(); if (pConvertedFrameBuffer != IntPtr.Zero) { Marshal.FreeHGlobal(pConvertedFrameBuffer); } if (_formatContext != null) { if (_formatContext->streams != null) { var j = (int)_formatContext->nb_streams; for (var i = j - 1; i >= 0; i--) { var stream = _formatContext->streams[i]; if (stream != null && stream->codec != null && stream->codec->codec != null) { stream->discard = AVDiscard.AVDISCARD_ALL; ffmpeg.avcodec_close(stream->codec); } } } fixed(AVFormatContext **f = &_formatContext) { ffmpeg.avformat_close_input(f); } _formatContext = null; } if (_videoFrame != null) { fixed(AVFrame **pinprt = &_videoFrame) { ffmpeg.av_frame_free(pinprt); _videoFrame = null; } } if (_audioFrame != null) { fixed(AVFrame **pinprt = &_audioFrame) { ffmpeg.av_frame_free(pinprt); _audioFrame = null; } } _videoStream = null; _audioStream = null; _audioCodecContext = null; _videoCodecContext = null; if (_swrContext != null) { fixed(SwrContext **s = &_swrContext) { ffmpeg.swr_free(s); } _swrContext = null; } if (pConvertContext != null) { ffmpeg.sws_freeContext(pConvertContext); } if (sampleChannel != null) { sampleChannel.PreVolumeMeter -= SampleChannelPreVolumeMeter; sampleChannel = null; } } catch (Exception ex) { Logger.LogException(ex, "Media Stream (close)"); } finally { try { Program.MutexHelper.Release(); } catch { } } PlayingFinished?.Invoke(this, new PlayingFinishedEventArgs(_res)); AudioFinished?.Invoke(this, new PlayingFinishedEventArgs(_res)); }
private IntPtr GetPointerToPointer() { return(Marshal.AllocHGlobal(MarshalHelpers.SizeOf <IntPtr>())); }
/// <summary> /// 通过NetBios获取MAC地址 /// </summary> /// <returns></returns> public static string GetMacAddressByNetBios() { string macAddress = ""; try { string addr = ""; int cb; ASTAT adapter; NCB Ncb = new NCB(); char uRetCode; LANA_ENUM lenum; Ncb.ncb_command = (byte)NCBCONST.NCBENUM; cb = Marshal.SizeOf(typeof(LANA_ENUM)); Ncb.ncb_buffer = Marshal.AllocHGlobal(cb); Ncb.ncb_length = (ushort)cb; uRetCode = Netbios(ref Ncb); lenum = (LANA_ENUM)Marshal.PtrToStructure(Ncb.ncb_buffer, typeof(LANA_ENUM)); Marshal.FreeHGlobal(Ncb.ncb_buffer); if (uRetCode != (short)NCBCONST.NRC_GOODRET) { return(""); } for (int i = 0; i < lenum.length; i++) { Ncb.ncb_command = (byte)NCBCONST.NCBRESET; Ncb.ncb_lana_num = lenum.lana[i]; uRetCode = Netbios(ref Ncb); if (uRetCode != (short)NCBCONST.NRC_GOODRET) { return(""); } Ncb.ncb_command = (byte)NCBCONST.NCBASTAT; Ncb.ncb_lana_num = lenum.lana[i]; Ncb.ncb_callname[0] = (byte)'*'; cb = Marshal.SizeOf(typeof(ADAPTER_STATUS)) + Marshal.SizeOf(typeof(NAME_BUFFER)) * (int)NCBCONST.NUM_NAMEBUF; Ncb.ncb_buffer = Marshal.AllocHGlobal(cb); Ncb.ncb_length = (ushort)cb; uRetCode = Netbios(ref Ncb); adapter.adapt = (ADAPTER_STATUS)Marshal.PtrToStructure(Ncb.ncb_buffer, typeof(ADAPTER_STATUS)); Marshal.FreeHGlobal(Ncb.ncb_buffer); if (uRetCode == (short)NCBCONST.NRC_GOODRET) { if (i > 0) { addr += ":"; } addr = string.Format("{0,2:X}:{1,2:X}:{2,2:X}:{3,2:X}:{4,2:X}:{5,2:X}", adapter.adapt.adapter_address[0], adapter.adapt.adapter_address[1], adapter.adapt.adapter_address[2], adapter.adapt.adapter_address[3], adapter.adapt.adapter_address[4], adapter.adapt.adapter_address[5]); } } macAddress = addr.Replace(' ', '0').Replace(":", string.Empty); } catch { } return(macAddress); }
/// <summary> /// reads an Input report from the device using interrupt transfers. /// </summary> /// /// <param name="hidHandle"> the handle for learning about the device and exchanging Feature reports. </param> /// <param name="readHandle"> the handle for reading Input reports from the device. </param> /// <param name="writeHandle"> the handle for writing Output reports to the device. </param> /// <param name="myDeviceDetected"> tells whether the device is currently attached. </param> /// <param name="inputReportBuffer"> contains the requested report. </param> /// <param name="success"> read success </param> internal override void Read(SafeFileHandle hidHandle, SafeFileHandle readHandle, SafeFileHandle writeHandle, ref Boolean myDeviceDetected, ref Byte[] inputReportBuffer, ref Boolean success) { IntPtr eventObject = IntPtr.Zero; NativeOverlapped HidOverlapped = new NativeOverlapped(); IntPtr nonManagedBuffer = IntPtr.Zero; IntPtr nonManagedOverlapped = IntPtr.Zero; Int32 numberOfBytesRead = 0; Int32 result = 0; try { // Set up the overlapped structure for ReadFile. PrepareForOverlappedTransfer(ref HidOverlapped, ref eventObject); // Allocate memory for the input buffer and overlapped structure. nonManagedBuffer = Marshal.AllocHGlobal(inputReportBuffer.Length); nonManagedOverlapped = Marshal.AllocHGlobal(Marshal.SizeOf(HidOverlapped)); Marshal.StructureToPtr(HidOverlapped, nonManagedOverlapped, false); // *** // API function: ReadFile // Purpose: Attempts to read an Input report from the device. // Accepts: // A device handle returned by CreateFile // (for overlapped I/O, CreateFile must have been called with FILE_FLAG_OVERLAPPED), // A pointer to a buffer for storing the report. // The Input report length in bytes returned by HidP_GetCaps, // A pointer to a variable that will hold the number of bytes read. // An overlapped structure whose hEvent member is set to an event object. // Returns: the report in ReadBuffer. // The overlapped call returns immediately, even if the data hasn't been received yet. // To read multiple reports with one ReadFile, increase the size of ReadBuffer // and use NumberOfBytesRead to determine how many reports were returned. // Use a larger buffer if the application can't keep up with reading each report // individually. // *** success = FileIO.ReadFile(readHandle, nonManagedBuffer, inputReportBuffer.Length, ref numberOfBytesRead, nonManagedOverlapped); if (!success) { Debug.WriteLine("waiting for ReadFile"); // API function: WaitForSingleObject // Purpose: waits for at least one report or a timeout. // Used with overlapped ReadFile. // Accepts: // An event object created with CreateEvent // A timeout value in milliseconds. // Returns: A result code. result = FileIO.WaitForSingleObject(eventObject, 3000); // Find out if ReadFile completed or timeout. switch (result) { case (System.Int32)FileIO.WAIT_OBJECT_0: // ReadFile has completed success = true; Debug.WriteLine("ReadFile completed successfully."); // Get the number of bytes read. // API function: GetOverlappedResult // Purpose: gets the result of an overlapped operation. // Accepts: // A device handle returned by CreateFile. // A pointer to an overlapped structure. // A pointer to a variable to hold the number of bytes read. // False to return immediately. // Returns: non-zero on success and the number of bytes read. FileIO.GetOverlappedResult(readHandle, nonManagedOverlapped, ref numberOfBytesRead, false); break; case FileIO.WAIT_TIMEOUT: // Cancel the operation on timeout CancelTransfer(hidHandle, readHandle, writeHandle, eventObject); Debug.WriteLine("Readfile timeout"); success = false; myDeviceDetected = false; break; default: // Cancel the operation on other error. CancelTransfer(hidHandle, readHandle, writeHandle, eventObject); Debug.WriteLine("Readfile undefined error"); success = false; myDeviceDetected = false; break; } } if (success) { // A report was received. // Copy the received data to inputReportBuffer for the application to use. Marshal.Copy(nonManagedBuffer, inputReportBuffer, 0, numberOfBytesRead); } } catch (Exception ex) { DisplayException(MODULE_NAME, ex); throw; } finally { if (nonManagedBuffer != IntPtr.Zero) { Marshal.FreeHGlobal(nonManagedBuffer); } if (nonManagedOverlapped != IntPtr.Zero) { Marshal.FreeHGlobal(nonManagedOverlapped); } } }
public WindowUpdate GetWindowUpdate(long windowHandle, out IDataInfo windowRenderData) { Desktop.SetCurrent(Desktop); List <Window> windows; try { //get all windows windows = Desktop.GetWindows().Where(x => NativeMethods.IsWindowVisible(x.Handle)).ToList(); } catch (Exception) { windowRenderData = null; return(null); } var windowUpdate = new WindowUpdate { AllWindows = windows.Select(x => x.Handle.ToInt64()).ToList() }; const int maxWindowNameLength = 100; var ptr = Marshal.AllocHGlobal(maxWindowNameLength); try { foreach (var window in windows) { RECT rect; NativeMethods.GetWindowRect(window.Handle, out rect); NativeMethods.GetWindowText(window.Handle, ptr, maxWindowNameLength); var windowInformation = new WindowInformation { Handle = (int)window.Handle, Height = rect.Height, Width = rect.Width, X = rect.X, Y = rect.Y, Title = Marshal.PtrToStringAnsi(ptr) }; var existingRenderWindow = _renderWindows.FirstOrDefault(x => x.WindowInformation.Handle == window.Handle.ToInt64()); if (existingRenderWindow == null) { windowUpdate.NewWindows.Add(windowInformation); _renderWindows.Add(new RenderWindow(windowInformation, window.Handle)); } else { if (existingRenderWindow.WindowInformation.Equals(windowInformation)) { continue; } windowUpdate.UpdatedWindows.Add(windowInformation); existingRenderWindow.ApplyWindowInformation(windowInformation); } } } finally { Marshal.FreeHGlobal(ptr); } var windowToRender = _renderWindows.FirstOrDefault(x => x.Handle.ToInt64() == windowHandle) ?? _renderWindows.FirstOrDefault(); //in case that _renderWindows is empty if (windowToRender != null) { windowRenderData = windowToRender.Render(); windowUpdate.RenderedWindowHandle = windowToRender.Handle.ToInt64(); } else { windowRenderData = null; } return(windowUpdate); }
/// <summary> /// Calculate some additional parameters needed for simulations /// </summary> public void Prepare() { if (Error != "") { return; } // min/max values of local coordinates double xmin = 1.0e6, xmax = -1.0e6, ymin = 1.0e6, ymax = -1.0e6, zmin = 1.0e6, zmax = -1.0e6; for (int i = 0; i < NAtoms; i++) { xmin = Math.Min(xmin, XLocal[i]); xmax = Math.Max(xmax, XLocal[i]); ymin = Math.Min(ymin, YLocal[i]); ymax = Math.Max(ymax, YLocal[i]); zmin = Math.Min(zmin, ZLocal[i]); zmax = Math.Max(zmax, ZLocal[i]); MaxRadius = new Vector3(Math.Max(MaxRadius.X, Math.Sqrt(YLocal[i] * YLocal[i] + ZLocal[i] * ZLocal[i]) + vdWR[i]), Math.Max(MaxRadius.Y, Math.Sqrt(XLocal[i] * XLocal[i] + ZLocal[i] * ZLocal[i]) + vdWR[i]), Math.Max(MaxRadius.Z, Math.Sqrt(XLocal[i] * XLocal[i] + YLocal[i] * YLocal[i]) + vdWR[i])); } // moment(s) of inertia double ixx = 0.0, iyy = 0.0, izz = 0.0, ixy = 0.0, ixz = 0.0, iyz = 0.0; double m = 0.0, x2, y2, z2; for (int i = 0; i < NAtoms; i++) { m = AtomMass[i]; x2 = XLocal[i] * XLocal[i]; y2 = YLocal[i] * YLocal[i]; z2 = ZLocal[i] * ZLocal[i]; ixx += m * (y2 + z2); iyy += m * (x2 + z2); izz += m * (x2 + y2); ixy -= m * XLocal[i] * YLocal[i]; ixz -= m * XLocal[i] * ZLocal[i]; iyz -= m * YLocal[i] * ZLocal[i]; } SimpleI = Math.Max(Math.Max(ixx, ixy), ixz); FullI = new Matrix3(ixx, ixy, ixz, ixy, iyy, iyz, ixz, iyz, izz); // clusters of clustersize^3 angstrom const double clustersize = 10.0; int nx, ny, nz, nxoff, nyoff, nzoff; nx = (int)(Math.Ceiling(xmax / clustersize) + Math.Ceiling(-xmin / clustersize)); ny = (int)(Math.Ceiling(ymax / clustersize) + Math.Ceiling(-ymin / clustersize)); nz = (int)(Math.Ceiling(zmax / clustersize) + Math.Ceiling(-zmin / clustersize)); nxoff = (int)Math.Ceiling(-xmin / clustersize); nyoff = (int)Math.Ceiling(-ymin / clustersize); nzoff = (int)Math.Ceiling(-zmin / clustersize); int nclusters = nx * ny * nz; AtomCluster[] atomcluster_tmp = new AtomCluster[nx * ny * nz]; // sort atoms // first run: count atoms in each cluster int nc, cNAtomsmax = 0; double rcsize = 1.0 / clustersize; for (int i = 0; i < NAtoms; i++) { nc = (int)(ZLocal[i] * rcsize + nzoff) + nz * ((int)(YLocal[i] * rcsize + nyoff) + ny * ((int)(XLocal[i] * rcsize + nxoff))); atomcluster_tmp[nc].NAtoms++; cNAtomsmax = Math.Max(cNAtomsmax, atomcluster_tmp[nc].NAtoms); } // allocate index arrays int ncfull = 0; int[][] originalatomindex = new int[nclusters][]; for (nc = 0; nc < nclusters; nc++) { if (atomcluster_tmp[nc].NAtoms > 0) { originalatomindex[nc] = new int[atomcluster_tmp[nc].NAtoms]; ncfull++; } } // fill int[] atomcounters = new int[nclusters]; for (int i = 0; i < NAtoms; i++) { nc = (int)(ZLocal[i] * rcsize + nzoff) + nz * ((int)(YLocal[i] * rcsize + nyoff) + ny * ((int)(XLocal[i] * rcsize + nxoff))); originalatomindex[nc][atomcounters[nc]++] = i; } // remove empty AtomClusters = new AtomCluster[ncfull]; ncfull = 0; for (nc = 0; nc < nclusters; nc++) { if (atomcluster_tmp[nc].NAtoms > 0) { originalatomindex[ncfull] = originalatomindex[nc]; AtomClusters[ncfull++] = atomcluster_tmp[nc]; } } // optimize each double rmax, cx, cy, cz; int ilocal; Vector3 rlocal; for (nc = 0; nc < AtomClusters.Length; nc++) { // get the center cx = 0.0; cy = 0.0; cz = 0.0; for (int i = 0; i < AtomClusters[nc].NAtoms; i++) { ilocal = originalatomindex[nc][i]; cx += XLocal[ilocal]; cy += YLocal[ilocal]; cz += ZLocal[ilocal]; } cx /= (double)AtomClusters[nc].NAtoms; cy /= (double)AtomClusters[nc].NAtoms; cz /= (double)AtomClusters[nc].NAtoms; AtomClusters[nc].ClusterCenter = new Vector3(cx, cy, cz); // find the most distant atom rmax = -1.0; for (int i = 0; i < AtomClusters[nc].NAtoms; i++) { ilocal = originalatomindex[nc][i]; rlocal = new Vector3(cx - XLocal[ilocal], cy - YLocal[ilocal], cz - ZLocal[ilocal]); rmax = Math.Max(Vector3.Abs(rlocal) + vdWR[ilocal], rmax); } AtomClusters[nc].ClusterRadius = rmax; } // try an alternative method : find a pair of most distant atoms for each dimension, try as a center int jlocal; double absr; for (nc = 0; nc < AtomClusters.Length; nc++) { rmax = -1.0; rlocal = AtomClusters[nc]; for (int i = 0; i < AtomClusters[nc].NAtoms; i++) { ilocal = originalatomindex[nc][i]; cx = XLocal[ilocal]; cy = YLocal[ilocal]; cz = ZLocal[ilocal]; for (int j = i + 1; j < AtomClusters[nc].NAtoms; j++) { jlocal = originalatomindex[nc][j]; rlocal = new Vector3(XLocal[jlocal] - cx, YLocal[jlocal] - cy, ZLocal[jlocal] - cz); absr = Vector3.Abs(rlocal); if (rmax < absr + vdWR[ilocal] + vdWR[jlocal]) { rmax = absr + vdWR[ilocal] + vdWR[jlocal]; rlocal = (absr == 0.0) ? new Vector3(cx, cy, cz) : new Vector3(cx, cy, cz) + rlocal * ((0.5 * rmax - vdWR[ilocal]) / absr); } } } // find the most distant atom rmax = -1.0; cx = rlocal.X; cy = rlocal.Y; cz = rlocal.Z; for (int i = 0; i < AtomClusters[nc].NAtoms; i++) { ilocal = originalatomindex[nc][i]; rlocal = new Vector3(cx - XLocal[ilocal], cy - YLocal[ilocal], cz - ZLocal[ilocal]); rmax = Math.Max(Vector3.Abs(rlocal) + vdWR[ilocal], rmax); } if (rmax < AtomClusters[nc].ClusterRadius) { AtomClusters[nc].ClusterCenter = new Vector3(cx, cy, cz); AtomClusters[nc].ClusterRadius = rmax; } } #if DEBUG if (DebugData.SaveAtomClusters) { // for debugging: save clusters xyz using (StreamWriter sw = new StreamWriter(this.Name + ".cluster.xyz", false)) { sw.WriteLine(AtomClusters.Length.ToString()); sw.WriteLine("cluster"); for (int i = 0; i < AtomClusters.Length; i++) { sw.WriteLine("L" + i.ToString() + " " + AtomClusters[i].ClusterCenter.X.ToString("F3") + " " + AtomClusters[i].ClusterCenter.Y.ToString("F3") + " " + AtomClusters[i].ClusterCenter.Z.ToString("F3")); } sw.Close(); } using (StreamWriter sw = new StreamWriter(this.Name + ".cluster.pml", false)) { sw.WriteLine("select all"); sw.WriteLine("translate [" + CM.X.ToString("F3") + "," + CM.Y.ToString("F3") + "," + CM.Z.ToString("F3") + "]"); sw.WriteLine("deselect"); for (int i = 0; i < AtomClusters.Length; i++) { sw.WriteLine("alter (name L" + i.ToString() + "), vdw=" + AtomClusters[i].ClusterRadius.ToString("F3")); } sw.Close(); } } #endif ///////////////////////////////////////////////////////////////////////////////////////// // remove atoms which can never be approached int nnbr, nblocked = 0; double[] xLocalnbr = new double[NAtoms]; double[] yLocalnbr = new double[NAtoms]; double[] zLocalnbr = new double[NAtoms]; double[] rthresh2 = new double[NAtoms]; double[] z2plus = new double[NAtoms]; double[] z2minus = new double[NAtoms]; double x0, y0, z0, rmin = AtomData.vdWRMin; Boolean[] atom_blocked = new Boolean[NAtoms]; Boolean accesible, zplus_blocked, zminus_blocked; double xg, yg, zg, rg, rxy, drmax, dtheta, dphi; for (int i = 0; i < NAtoms; i++) { accesible = false; x0 = XLocal[i]; y0 = YLocal[i]; z0 = ZLocal[i]; rmax = 2.0 * rmin + vdWR[i]; // select neighbours within r1 + r2 + 2rmin nnbr = 0; for (int j = 0; j < NAtoms; j++) { x2 = (XLocal[j] - x0) * (XLocal[j] - x0); y2 = (YLocal[j] - y0) * (YLocal[j] - y0); z2 = (ZLocal[j] - z0) * (ZLocal[j] - z0); if (x2 + y2 + z2 < (rmax + vdWR[j]) * (rmax + vdWR[j])) { xLocalnbr[nnbr] = XLocal[j] - x0; yLocalnbr[nnbr] = YLocal[j] - y0; zLocalnbr[nnbr] = ZLocal[j] - z0; rthresh2[nnbr++] = (0.9 * rmin + vdWR[j]) * (0.9 * rmin + vdWR[j]); } } // spherical grid rg = vdWR[i] + rmin; drmax = 0.1 * rmin / rg; nz = (int)Math.Ceiling(Math.PI / drmax); dtheta = Math.PI / nz; for (double theta = Math.PI / 2.0; theta >= 0.0; theta -= dtheta) { zg = rg * Math.Sin(theta); for (int j = 0; j < nnbr; j++) { z2plus[j] = (zLocalnbr[j] - zg) * (zLocalnbr[j] - zg); z2minus[j] = (zLocalnbr[j] + zg) * (zLocalnbr[j] + zg); } rxy = rg * Math.Cos(theta); dphi = (rxy > 0.05 * rmin / Math.PI) ? 0.1 * rmin / rxy : 2.0 * Math.PI; for (double phi = 0.0; phi <= 2.0 * Math.PI; phi += dphi) { xg = rxy * Math.Cos(phi); yg = rxy * Math.Sin(phi); // check all neighbours at zg and -zg zplus_blocked = false; zminus_blocked = false; for (int j = 0; j < nnbr; j++) { x2 = (xLocalnbr[j] - xg) * (xLocalnbr[j] - xg); y2 = (yLocalnbr[j] - yg) * (yLocalnbr[j] - yg); zplus_blocked = zplus_blocked || (x2 + y2 + z2plus[j] < rthresh2[j]); zminus_blocked = zminus_blocked || (x2 + y2 + z2minus[j] < rthresh2[j]); if (zplus_blocked && zminus_blocked) { break; } } accesible = accesible || (!zplus_blocked) || (!zminus_blocked); if (accesible) { break; } } if (accesible) { break; } } atom_blocked[i] = !accesible; nblocked = accesible ? nblocked : nblocked + 1; } // finally remove blocked atoms and reorder int ai = 0, unblocked = NAtoms - nblocked; MaxAtomsInCluster = 0; for (nc = 0; nc < AtomClusters.Length; nc++) { // first run: count blocked atoms nblocked = 0; // now in cluster nc for (int i = 0; i < AtomClusters[nc].NAtoms; i++) { nblocked = atom_blocked[originalatomindex[nc][i]] ? nblocked + 1 : nblocked; } // second run: fill ai = 0; for (int i = 0; i < AtomClusters[nc].NAtoms; i++) { ilocal = originalatomindex[nc][i]; if (!atom_blocked[ilocal]) { originalatomindex[nc][ai++] = ilocal; } } AtomClusters[nc].NAtoms -= nblocked; MaxAtomsInCluster = Math.Max(MaxAtomsInCluster, AtomClusters[nc].NAtoms); } // fill cluster arrays this.ClusteredAtomXYZ = new Vector3[unblocked]; this.ClusteredAtomvdwR = new double[unblocked]; this.ClusteredAtomOriginalIndex = new int[unblocked]; if (XYZvdwRVectorArray != IntPtr.Zero) { Marshal.FreeHGlobal(XYZvdwRVectorArray); } XYZvdwRVectorArray = Marshal.AllocHGlobal((unblocked + 1) * sizeof(float) * 4); float[] XYZvdwRdata = new float[unblocked * 4]; int idata = 0, idata4 = 0, oi; for (nc = 0; nc < AtomClusters.Length; nc++) { AtomClusters[nc].StartIndexInClusterArrays = idata; for (int i = 0; i < AtomClusters[nc].NAtoms; i++) { oi = originalatomindex[nc][i]; ClusteredAtomXYZ[idata] = new Vector3(XLocal[oi], YLocal[oi], ZLocal[oi]); ClusteredAtomvdwR[idata] = vdWR[oi]; ClusteredAtomOriginalIndex[idata++] = oi; XYZvdwRdata[idata4++] = (float)XLocal[oi]; XYZvdwRdata[idata4++] = (float)YLocal[oi]; XYZvdwRdata[idata4++] = (float)ZLocal[oi]; XYZvdwRdata[idata4++] = (float)vdWR[oi]; } } Marshal.Copy(XYZvdwRdata, 0, FpsNativeWrapper.Aligned16(XYZvdwRVectorArray), XYZvdwRdata.Length); Prepared = true; }
/// <summary> /// Constructor /// </summary> /// <param name="allocation_length">The length of data to allocate.</param> /// <param name="total_length">The total length to reflect in the Length property.</param> protected SafeHGlobalBuffer(int allocation_length, int total_length) : this(Marshal.AllocHGlobal(allocation_length), total_length, true) { }
public static IntPtr Allocate(SVMModel x) { if (x == null || x.ClassCount < 1 || x.Parameter == null || x.Rho == null || x.Rho.Length < 1 || x.SVCoefs == null || x.SVCoefs.Count < 1 || x.TotalSVCount < 1) { return(IntPtr.Zero); } if (x.Parameter.Type != SVMType.EPSILON_SVR && x.Parameter.Type != SVMType.NU_SVR && x.Parameter.Type != SVMType.ONE_CLASS && (x.Labels == null || x.Labels.Length < 1 || x.SVCounts == null || x.SVCounts.Length < 1)) { return(IntPtr.Zero); } svm_model y = new svm_model(); y.nr_class = x.ClassCount; y.l = x.TotalSVCount; y.free_sv = (int)x.Creation; // Allocate model.parameter IntPtr ptr_param = SVMParameter.Allocate(x.Parameter); y.param = (svm_parameter)Marshal.PtrToStructure(ptr_param, typeof(svm_parameter)); //SVMParameter.Free(ptr_param); // Allocate model.rho y.rho = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(double)) * x.Rho.Length); Marshal.Copy(x.Rho, 0, y.rho, x.Rho.Length); // Allocate model.probA y.probA = IntPtr.Zero; if (x.ProbabilityA != null) { y.probA = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(double)) * x.ProbabilityA.Length); Marshal.Copy(x.ProbabilityA, 0, y.probA, x.ProbabilityA.Length); } // Allocate model.probB y.probB = IntPtr.Zero; if (x.ProbabilityB != null) { y.probB = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(double)) * x.ProbabilityB.Length); Marshal.Copy(x.ProbabilityB, 0, y.probB, x.ProbabilityB.Length); } if (x.Parameter.Type != SVMType.EPSILON_SVR && x.Parameter.Type != SVMType.NU_SVR && x.Parameter.Type != SVMType.ONE_CLASS) { // Allocate model.label y.label = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(int)) * x.Labels.Length); Marshal.Copy(x.Labels, 0, y.label, x.Labels.Length); // Allocate model.nSV y.nSV = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(int)) * x.SVCounts.Length); Marshal.Copy(x.SVCounts, 0, y.nSV, x.SVCounts.Length); } else { y.label = IntPtr.Zero; y.nSV = IntPtr.Zero; } // Allocate model.sv_coef y.sv_coef = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(IntPtr)) * x.SVCoefs.Count); IntPtr i_ptr_svcoef = y.sv_coef; for (int i = 0; i < x.SVCoefs.Count; i++) { IntPtr temp = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(double)) * x.SVCoefs[i].Length); Marshal.Copy(x.SVCoefs[i], 0, temp, x.SVCoefs[i].Length); Marshal.StructureToPtr(temp, i_ptr_svcoef, true); i_ptr_svcoef = IntPtr.Add(i_ptr_svcoef, Marshal.SizeOf(typeof(IntPtr))); } // Allocate model.sv_indices y.sv_indices = IntPtr.Zero; if (x.SVIndices != null) { y.sv_indices = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(int)) * x.SVIndices.Length); Marshal.Copy(x.SVIndices, 0, y.sv_indices, x.SVIndices.Length); } // Allocate model.SV y.SV = IntPtr.Zero; if (x.SV != null) { y.SV = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(IntPtr)) * x.SV.Count); IntPtr i_ptr_sv = y.SV; for (int i = 0; i < x.SV.Count; i++) { // Prepare each node array // 1) All nodes containing zero value is removed // 2) A node which index is -1 is added to the end List <SVMNode> temp = x.SV[i].Where(a => a.Value != 0).ToList(); temp.Add(new SVMNode(-1, 0)); SVMNode[] nodes = temp.ToArray(); // Allocate node array IntPtr ptr_nodes = SVMNode.Allocate(nodes); Marshal.StructureToPtr(ptr_nodes, i_ptr_sv, true); i_ptr_sv = IntPtr.Add(i_ptr_sv, Marshal.SizeOf(typeof(IntPtr))); } } // Allocate the model int size = Marshal.SizeOf(y); IntPtr ptr = Marshal.AllocHGlobal(size); Marshal.StructureToPtr(y, ptr, true); return(ptr); }
public void getAuthGroup(IntPtr sdkContext, uint deviceID, bool isMasterDevice) { IntPtr authGroupObj = IntPtr.Zero; UInt32 numAuthGroup = 0; BS2ErrorCode result = BS2ErrorCode.BS_SDK_SUCCESS; Console.WriteLine("Do you want to get all auth groups? [Y/n]"); Console.Write(">>>> "); if (Util.IsYes()) { Console.WriteLine("Trying to get all auth gruops from device."); result = (BS2ErrorCode)API.BS2_GetAllAuthGroup(sdkContext, deviceID, out authGroupObj, out numAuthGroup); } else { Console.WriteLine("Enter the ID of the access group which you want to get: [ID_1,ID_2 ...]"); Console.Write(">>>> "); char[] delimiterChars = { ' ', ',', '.', ':', '\t' }; string[] authGroupIDs = Console.ReadLine().Split(delimiterChars); List <UInt32> authGroupIDList = new List <UInt32>(); foreach (string authGroupID in authGroupIDs) { if (authGroupID.Length > 0) { UInt32 item; if (UInt32.TryParse(authGroupID, out item)) { authGroupIDList.Add(item); } } } if (authGroupIDList.Count > 0) { IntPtr authGroupIDObj = Marshal.AllocHGlobal(4 * authGroupIDList.Count); IntPtr curAuthGroupIDObj = authGroupIDObj; foreach (UInt32 item in authGroupIDList) { Marshal.WriteInt32(curAuthGroupIDObj, (Int32)item); curAuthGroupIDObj = (IntPtr)((long)curAuthGroupIDObj + 4); } Console.WriteLine("Trying to get auth gruops from device."); result = (BS2ErrorCode)API.BS2_GetAuthGroup(sdkContext, deviceID, authGroupIDObj, (UInt32)authGroupIDList.Count, out authGroupObj, out numAuthGroup); Marshal.FreeHGlobal(authGroupIDObj); } else { Console.WriteLine("Invalid parameter"); } } if (result != BS2ErrorCode.BS_SDK_SUCCESS) { Console.WriteLine("Got error({0}).", result); } else if (numAuthGroup > 0) { IntPtr curAuthGroupObj = authGroupObj; int structSize = Marshal.SizeOf(typeof(BS2AuthGroup)); for (int idx = 0; idx < numAuthGroup; ++idx) { BS2AuthGroup item = (BS2AuthGroup)Marshal.PtrToStructure(curAuthGroupObj, typeof(BS2AuthGroup)); print(sdkContext, item); curAuthGroupObj = (IntPtr)((long)curAuthGroupObj + structSize); } API.BS2_ReleaseObject(authGroupObj); } else { Console.WriteLine(">>> There is no auth group in the device."); } }
public string read() { //Get data from registry string regstring = (string)regkey.GetValue(RegKeys.DPAPISTORAGESUBVALUE);; bool retVal = false; DATA_BLOB plainTextBlob = new DATA_BLOB(); DATA_BLOB cipherBlob = new DATA_BLOB(); CRYPTPROTECT_PROMPTSTRUCT prompt = new CRYPTPROTECT_PROMPTSTRUCT(); InitPromptstruct(ref prompt); byte[] cipherText = Convert.FromBase64String(regstring); byte[] entropyText = System.Text.Encoding.Unicode.GetBytes(_entropy); try { try { int cipherTextSize = cipherText.Length; cipherBlob.pbData = Marshal.AllocHGlobal(cipherTextSize); if (cipherBlob.pbData == IntPtr.Zero) { throw new OutOfMemoryException("Unable to allocate cipherText buffer."); } cipherBlob.cbData = cipherTextSize; Marshal.Copy(cipherText, 0, cipherBlob.pbData, cipherBlob.cbData); } catch (Exception ex) { throw new Exception("Exception marshalling data.", ex); } DATA_BLOB entropyBlob = new DATA_BLOB(); // MachineStore int dwFlags = CRYPTPROTECT_LOCAL_MACHINE | CRYPTPROTECT_UI_FORBIDDEN; try { int bytesSize = entropyText.Length; entropyBlob.pbData = Marshal.AllocHGlobal(bytesSize); if (entropyBlob.pbData == IntPtr.Zero) { throw new OutOfMemoryException("Unable to allocate entropy buffer."); } entropyBlob.cbData = bytesSize; Marshal.Copy(entropyText, 0, entropyBlob.pbData, bytesSize); } catch (Exception ex) { throw new Exception("Exception entropy marshalling data. ", ex); } retVal = CryptUnprotectData(ref cipherBlob, null, ref entropyBlob, IntPtr.Zero, ref prompt, dwFlags, ref plainTextBlob); if (!retVal) { Win32Exception w32e = new Win32Exception(Marshal.GetLastWin32Error()); throw new ApplicationException("Decryption failed. " + w32e.Message); } //Free the blob and entropy. if (cipherBlob.pbData != IntPtr.Zero) { Marshal.FreeHGlobal(cipherBlob.pbData); } if (entropyBlob.pbData != IntPtr.Zero) { Marshal.FreeHGlobal(entropyBlob.pbData); } } catch (Exception ex) { throw new Exception("Exception decrypting.", ex); } byte[] plainText = new byte[plainTextBlob.cbData]; Marshal.Copy(plainTextBlob.pbData, plainText, 0, plainTextBlob.cbData); return(Encoding.Unicode.GetString(plainText)); }
/// <summary> /// Scans for all attached removable devices /// </summary> public Task <IEnumerable <InstalledMountedDriveInfo> > ScanAttachedDrivesAsync() { var installedMountedDrives = new SortedList <string, InstalledMountedDriveInfo>(); try { var environmentDrives = new Hashtable(); var mountedDrives = new Hashtable(); foreach (var drive in Environment.GetLogicalDrives()) { environmentDrives.Add(drive, new DriveInfo(drive)); } var mountedDevices = Registry.LocalMachine.OpenSubKey("SYSTEM\\MountedDevices"); if (mountedDevices?.ValueCount > 0) { var mountedDeviceNames = mountedDevices.GetValueNames() .Where(name => name.StartsWith("\\DosDevices\\")); foreach (var mountedDeviceName in mountedDeviceNames) { var driveLetter = new StringBuilder(mountedDeviceName.Substring(12)); driveLetter.Append("\\"); if (!environmentDrives.ContainsKey(driveLetter.ToString())) { continue; } var thisDriveInfo = (DriveInfo)environmentDrives[driveLetter.ToString()]; if (thisDriveInfo.DriveType != DriveType.Removable) { continue; } var bytes = (byte[])mountedDevices.GetValue(mountedDeviceName); var cleaned = new byte[bytes.Length - 1]; var pointer = 0; var firstSlashFound = false; var secondSlashFound = false; var questionMarkFound = false; foreach (var character in (byte[])mountedDevices.GetValue(mountedDeviceName)) { if (character == 0) { continue; } if (firstSlashFound) { if (questionMarkFound) { if (secondSlashFound) { cleaned[pointer] = character; pointer++; } else { if (character == 92) { secondSlashFound = true; } } } else { if (character == 63) { questionMarkFound = true; } } } else { if (character == 92) { firstSlashFound = true; } } } var finished = new byte[pointer]; for (var i = 0; i < pointer; i++) { finished[i] = cleaned[i]; } mountedDrives.Add(driveLetter, new MountedDriveInfo(thisDriveInfo, Encoding.Default.GetString(finished).ToUpper())); } } mountedDevices?.Close(); var classGuid = new Guid(UnsafeNativeMethods.GUID_DEVINTERFACE_VOLUME); var deviceInfoSet = UnsafeNativeMethods.SetupDiGetClassDevs(ref classGuid, 0, IntPtr.Zero, UnsafeNativeMethods.DIGCF_DEVICEINTERFACE | UnsafeNativeMethods.DIGCF_PRESENT); if (deviceInfoSet.ToInt32() == UnsafeNativeMethods.INVALID_HANDLE_VALUE) { return(Task.FromResult(Enumerable.Empty <InstalledMountedDriveInfo>())); } var index = 0; while (true) { var size = 0; var interfaceData = new UnsafeNativeMethods.SP_DEVICE_INTERFACE_DATA(); var devData = new UnsafeNativeMethods.SP_DEVINFO_DATA(); var detailData = new UnsafeNativeMethods.SP_DEVICE_INTERFACE_DETAIL_DATA(); if ( !UnsafeNativeMethods.SetupDiEnumDeviceInterfaces(deviceInfoSet, null, ref classGuid, index, interfaceData)) { break; } UnsafeNativeMethods.SetupDiGetDeviceInterfaceDetail(deviceInfoSet, interfaceData, IntPtr.Zero, 0, ref size, devData); var buffer = Marshal.AllocHGlobal(size); // for 64 bit system, the size needs to be 8, for 32 bit system, the size needs to be 5 if (IntPtr.Size == 8) { detailData.cbSize = 8; } else { detailData.cbSize = Marshal.SizeOf(typeof(UnsafeNativeMethods.SP_DEVICE_INTERFACE_DETAIL_DATA)); } Marshal.StructureToPtr(detailData, buffer, false); if (!UnsafeNativeMethods.SetupDiGetDeviceInterfaceDetail(deviceInfoSet, interfaceData, buffer, size, ref size, devData)) { Marshal.FreeHGlobal(buffer); } var pDevicePath = (IntPtr)((int)buffer + Marshal.SizeOf(typeof(int))); var devicePath = Marshal.PtrToStringAuto(pDevicePath); if (devicePath != null) { devicePath = devicePath.ToUpper(); Marshal.FreeHGlobal(buffer); foreach (MountedDriveInfo mountedDrive in mountedDrives.Values) { if (!devicePath.Contains(mountedDrive.RegistryInfo)) { continue; } var thisMountedDrive = new InstalledMountedDriveInfo(mountedDrive.DriveInfo, devData.devInst, (UnsafeNativeMethods.DeviceCapabilities) UnsafeNativeMethods.GetProperty(deviceInfoSet, devData, UnsafeNativeMethods.SPDRP_CAPABILITIES, 0), UnsafeNativeMethods.GetProperty(deviceInfoSet, devData, UnsafeNativeMethods.SPDRP_PHYSICAL_DEVICE_OBJECT_NAME, "bad name")); try { // Check attempts to add duplicate drives when the SetupDiEnumDeviceInterfaces call does not break // on first call for a particular drive (multiple device interfaces). if (installedMountedDrives.ContainsKey(thisMountedDrive.Description) == false) { installedMountedDrives.Add(thisMountedDrive.Description, thisMountedDrive); } } catch (Exception) { // Ignore unspecified exceptions and continue building mounted drives } } } index++; } } catch (Exception ex) { _logger.Log(ex); } _events.GetEvent <ScanDrivesCompletedEvent>().Publish(installedMountedDrives.Values.AsEnumerable()); return(Task.FromResult(installedMountedDrives.Values.AsEnumerable())); }
public void write(string connString) { bool retVal = false; DATA_BLOB plainTextBlob = new DATA_BLOB(); DATA_BLOB cipherTextBlob = new DATA_BLOB(); DATA_BLOB entropyBlob = new DATA_BLOB(); CRYPTPROTECT_PROMPTSTRUCT prompt = new CRYPTPROTECT_PROMPTSTRUCT(); InitPromptstruct(ref prompt); byte[] plainText = System.Text.Encoding.Unicode.GetBytes(connString); byte[] entropyText = System.Text.Encoding.Unicode.GetBytes(_entropy); int dwFlags; try { try { try { int bytesSize = plainText.Length; plainTextBlob.pbData = Marshal.AllocHGlobal(bytesSize); if (plainTextBlob.pbData == IntPtr.Zero) { throw new OutOfMemoryException("Unable to allocate memory for buffer."); } plainTextBlob.cbData = bytesSize; Marshal.Copy(plainText, 0, plainTextBlob.pbData, bytesSize); } catch (Exception ex) { throw new Exception("Exception marshalling data.", ex); } // MachineStore dwFlags = CRYPTPROTECT_LOCAL_MACHINE | CRYPTPROTECT_UI_FORBIDDEN; try { int bytesSize = entropyText.Length; entropyBlob.pbData = Marshal.AllocHGlobal(bytesSize); if (entropyBlob.pbData == IntPtr.Zero) { throw new OutOfMemoryException("Unable to allocate entropy data buffer."); } Marshal.Copy(entropyText, 0, entropyBlob.pbData, bytesSize); entropyBlob.cbData = bytesSize; retVal = CryptProtectData(ref plainTextBlob, null, ref entropyBlob, IntPtr.Zero, ref prompt, dwFlags, ref cipherTextBlob); if (!retVal) { Win32Exception w32e = new Win32Exception(Marshal.GetLastWin32Error()); throw new ApplicationException("Encryption failed. " + w32e.Message); } } catch (Exception ex) { throw new Exception("Exception entropy marshalling data. ", ex); } } catch (Exception ex) { throw new Exception("Exception marshalling data.", ex); } byte[] cipherText = new byte[cipherTextBlob.cbData]; Marshal.Copy(cipherTextBlob.pbData, cipherText, 0, cipherTextBlob.cbData); regkey.SetValue(RegKeys.DPAPISTORAGESUBVALUE, Convert.ToBase64String(cipherText)); } catch (Exception ex) { throw new Exception("Exception storing data.", ex); } }
public void BeginTransaction(TransactionParameterBuffer tpb) { if (_state != TransactionState.NoTransaction) { throw new IscException(IscCodes.isc_arg_gds, IscCodes.isc_tra_state, _handle, "no valid"); } lock (_db) { IscTeb teb = new IscTeb(); IntPtr tebData = IntPtr.Zero; try { // Clear the status vector ClearStatusVector(); // Set db handle teb.dbb_ptr = Marshal.AllocHGlobal(4); Marshal.WriteInt32(teb.dbb_ptr, _db.Handle); // Set tpb length teb.tpb_len = tpb.Length; // Set TPB data teb.tpb_ptr = Marshal.AllocHGlobal(tpb.Length); Marshal.Copy(tpb.ToArray(), 0, teb.tpb_ptr, tpb.Length); // Alloc memory for the IscTeb structure int size = Marshal.SizeOf(typeof(IscTeb)); tebData = Marshal.AllocHGlobal(size); Marshal.StructureToPtr(teb, tebData, true); int trHandle = _handle; _db.FbClient.isc_start_multiple( _statusVector, ref trHandle, 1, tebData); _handle = trHandle; // Parse status vector _db.ParseStatusVector(_statusVector); // Update transaction state _state = TransactionState.Active; // Update transaction count _db.TransactionCount++; } catch { throw; } finally { // Free memory if (teb.dbb_ptr != IntPtr.Zero) { Marshal.FreeHGlobal(teb.dbb_ptr); } if (teb.tpb_ptr != IntPtr.Zero) { Marshal.FreeHGlobal(teb.tpb_ptr); } if (tebData != IntPtr.Zero) { Marshal.DestroyStructure(tebData, typeof(IscTeb)); Marshal.FreeHGlobal(tebData); } } } }
public void CouldUseSMFormulaCorrectly() { BLAS.BlasNumThreads = 1; // Calculate (X'X)^-1 for M and M-1 var dataSpan = new Span <double>(Data, Columns * Rows); var rounds = 3; var count = 20; var rows = new[] { 2, 4, 6, 8, 10, 15, 20, 30, 40, 50, 60, 70, 80, 90, 100, 200, 300, 400, 500 }; var columns = new[] { 2, 4, 6, 8, 10, 15, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 200, 300, 400, 500 }; var syrkVsGemm = new bool[rows.Length, columns.Length]; Console.Write($" "); foreach (var co in columns) { Console.Write($"{co} "); } Console.WriteLine(); foreach (var ro in rows) { Console.Write($"{ro}: "); foreach (var co in columns) { Rows = ro; Columns = co; Marshal.FreeHGlobal((IntPtr)Data); SetUp(); var xxN = (double *)Marshal.AllocHGlobal(Columns * Columns * 8); var xxN1 = (double *)Marshal.AllocHGlobal(Columns * Columns * 8); var xxNSpan = new Span <double>(xxN, Columns * Columns); var xxN1Span = new Span <double>(xxN1, Columns * Columns); var flopsMult = 1L * Columns * Columns * Rows * 2; for (int r = 0; r < rounds; r++) { var statGemm = Benchmark.Run($"Dgemm_{ro}x{co}", count * flopsMult, silent: true); { for (int i = 0; i < count; i++) { var data = Data; CBLAS.Dgemm(LAYOUT.RowMajor, TRANSPOSE.Trans, TRANSPOSE.NoTrans, Columns, Columns, Rows, alpha: 1.0, data, Columns, data, Columns, beta: 0.0, xxN, Columns); } } statGemm.Dispose(); var starSyrk = Benchmark.Run($"Dsyrk_{ro}x{co}", count * flopsMult, silent: true); { for (int i = 0; i < count; i++) { var data = Data; CBLAS.Dsyrk(LAYOUT.RowMajor, UPLO.Upper, TRANSPOSE.Trans, Columns, Rows, 1.0, data, Columns, 0.0, xxN, Columns); } } starSyrk.Dispose(); if (r == rounds - 1) { // Console.WriteLine($"starSyrk.MOPS {starSyrk.MOPS} - starGemm.MOPS {statGemm.MOPS}"); if (starSyrk.MOPS > statGemm.MOPS) { // syrkVsGemm[ro, co] = true; Console.Write(1 + " "); } else { Console.Write(0 + " "); } } } } Console.WriteLine(); } // Benchmark.Dump(); // CBLAS.Dsyrk(LAYOUT.RowMajor, UPLO.Lower, TRANSPOSE.Trans, Columns, Rows - 1, 1.0, Data, Rows, 0.0, xxN1, Columns); }
/// <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)) { Directory.CreateDirectory(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 Object(); //if(!isSymLink) if (true) { reparseDataBuffer = new REPARSE_DATA_BUFFER_MOUNT_POINT { 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, ((REPARSE_DATA_BUFFER_MOUNT_POINT)reparseDataBuffer).PathBuffer, targetDirBytes.Length); } /* * else * { * reparseDataBuffer = * new REPARSE_DATA_BUFFER_SYM_LINK * { * ReparseTag = IO_REPARSE_TAG_SYMLINK, * ReparseDataLength = (ushort)(targetDirBytes.Length + 12), * SubstituteNameOffset = 0, * SubstituteNameLength = (ushort)targetDirBytes.Length, * PrintNameOffset = (ushort)(targetDirBytes.Length + 2), * PrintNameLength = 0, * Flags = 0, * PathBuffer = new byte[0x3ff0] * }; * Array.Copy(targetDirBytes, ((REPARSE_DATA_BUFFER_SYM_LINK)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); } } }
public static DeviceInfo[] GetInterfaces() { var list = new List <DeviceInfo>(); Guid hidGuid = Guid.Empty; NativeMethods.HidD_GetHidGuid(ref hidGuid); int requiredSize3 = 0; List <string> devicePathNames3 = new List <string>(); var interfaceData = new SP_DEVICE_INTERFACE_DATA(); List <string> serials = new List <string>(); interfaceData.Initialize(); var deviceInfoSet = NativeMethods.SetupDiGetClassDevs(hidGuid, IntPtr.Zero, IntPtr.Zero, DIGCF.DIGCF_DEVICEINTERFACE); for (int i2 = 0; NativeMethods.SetupDiEnumDeviceInterfaces(deviceInfoSet, IntPtr.Zero, ref hidGuid, i2, ref interfaceData); i2++) { var deviceInfoData = new SP_DEVINFO_DATA(); deviceInfoData.Initialize(); bool success = NativeMethods.SetupDiGetDeviceInterfaceDetail(deviceInfoSet, ref interfaceData, IntPtr.Zero, 0, ref requiredSize3, IntPtr.Zero); IntPtr ptrDetails = Marshal.AllocHGlobal(requiredSize3); Marshal.WriteInt32(ptrDetails, (IntPtr.Size == 4) ? (4 + Marshal.SystemDefaultCharSize) : 8); success = NativeMethods.SetupDiGetDeviceInterfaceDetail(deviceInfoSet, ref interfaceData, ptrDetails, requiredSize3, ref requiredSize3, ref deviceInfoData); var interfaceDetail = (SP_DEVICE_INTERFACE_DETAIL_DATA)Marshal.PtrToStructure(ptrDetails, typeof(SP_DEVICE_INTERFACE_DETAIL_DATA)); var devicePath = interfaceDetail.DevicePath; var deviceId = GetDeviceId(deviceInfoData.DevInst); devicePathNames3.Add(devicePath); Marshal.FreeHGlobal(ptrDetails); var accessRights = WinNT.GENERIC_READ | WinNT.GENERIC_WRITE; var shareModes = WinNT.FILE_SHARE_READ | WinNT.FILE_SHARE_WRITE; // Open the device as a file so that we can query it with HID and read/write to it. var devHandle = NativeMethods.CreateFile( interfaceDetail.DevicePath, accessRights, shareModes, IntPtr.Zero, WinNT.OPEN_EXISTING, WinNT.Overlapped, IntPtr.Zero ); if (devHandle.IsInvalid) { continue; } var ha = new HIDD_ATTRIBUTES(); ha.Size = Marshal.SizeOf(ha); var success2 = NativeMethods.HidD_GetAttributes(devHandle, ref ha); string serial = ""; string vendor = ""; string product = ""; string phdesc = ""; if (success2) { IntPtr preparsedDataPtr = new IntPtr(); HIDP_CAPS caps = new HIDP_CAPS(); // Read out the 'preparsed data'. NativeMethods.HidD_GetPreparsedData(devHandle, ref preparsedDataPtr); // feed that to GetCaps. NativeMethods.HidP_GetCaps(preparsedDataPtr, ref caps); // Free the 'preparsed data'. NativeMethods.HidD_FreePreparsedData(ref preparsedDataPtr); // This could fail if the device was recently attached. uint capacity = 126; IntPtr buffer = Marshal.AllocHGlobal((int)capacity); serial = NativeMethods.HidD_GetSerialNumberString(devHandle, buffer, capacity) ? Marshal.PtrToStringAuto(buffer) : ""; vendor = NativeMethods.HidD_GetManufacturerString(devHandle, buffer, capacity) ? Marshal.PtrToStringAuto(buffer) : ""; product = NativeMethods.HidD_GetProductString(devHandle, buffer, capacity) ? Marshal.PtrToStringAuto(buffer) : ""; phdesc = NativeMethods.HidD_GetPhysicalDescriptor(devHandle, buffer, capacity) ? Marshal.PtrToStringAuto(buffer) : ""; // Free resources. Marshal.FreeHGlobal(buffer); } uint parentDeviceInstance = 0; string parentDeviceId = null; var CRResult = NativeMethods.CM_Get_Parent(out parentDeviceInstance, deviceInfoData.DevInst, 0); if (CRResult == CR.CR_SUCCESS) { parentDeviceId = GetDeviceId(parentDeviceInstance); } var di = new DeviceInfo(deviceId, parentDeviceId, devicePath, vendor, product, hidGuid, "", DeviceNodeStatus.DN_MANUAL, ha.VendorID, ha.ProductID, ha.VersionNumber); list.Add(di); serials.Add(phdesc); devHandle.Close(); } NativeMethods.SetupDiDestroyDeviceInfoList(deviceInfoSet); deviceInfoSet = IntPtr.Zero; return(list.ToArray()); }
public void Initialize(ICallbackable callbackable) { callbackable.Shadow = this; var type = callbackable.GetType(); List <Type> slimInterfaces; // Cache reflection on COM interface inheritance lock (typeToShadowTypes) { if (!typeToShadowTypes.TryGetValue(type, out slimInterfaces)) { #if !NET_45 var interfaces = type.GetTypeInfo().GetInterfaces(); #else var interfaces = type.GetTypeInfo().ImplementedInterfaces; #endif slimInterfaces = new List <Type>(); slimInterfaces.AddRange(interfaces); typeToShadowTypes.Add(type, slimInterfaces); // First pass to identify most detailed interfaces foreach (var item in interfaces) { // Only process interfaces that are using shadow var shadowAttribute = ShadowAttribute.Get(item); if (shadowAttribute == null) { slimInterfaces.Remove(item); continue; } // Keep only final interfaces and not intermediate. #if !NET_45 var inheritList = item.GetTypeInfo().GetInterfaces(); #else var inheritList = item.GetTypeInfo().ImplementedInterfaces; #endif foreach (var inheritInterface in inheritList) { slimInterfaces.Remove(inheritInterface); } } } } CppObjectShadow iunknownShadow = null; // Second pass to instantiate shadow foreach (var item in slimInterfaces) { // Only process interfaces that are using shadow var shadowAttribute = ShadowAttribute.Get(item); // Initialize the shadow with the callback var shadow = (CppObjectShadow)Activator.CreateInstance(shadowAttribute.Type); shadow.Initialize(callbackable); // Take the first shadow as the main IUnknown if (iunknownShadow == null) { iunknownShadow = shadow; // Add IUnknown as a supported interface guidToShadow.Add(ComObjectShadow.IID_IUnknown, iunknownShadow); } guidToShadow.Add(Utilities.GetGuidFromType(item), shadow); // Associate also inherited interface to this shadow #if !NET_45 var inheritList = item.GetTypeInfo().GetInterfaces(); #else var inheritList = item.GetTypeInfo().ImplementedInterfaces; #endif foreach (var inheritInterface in inheritList) { var inheritShadowAttribute = ShadowAttribute.Get(inheritInterface); if (inheritShadowAttribute == null) { continue; } // Use same shadow as derived guidToShadow.Add(Utilities.GetGuidFromType(inheritInterface), shadow); } } // Precalculate the list of GUID without IUnknown and IInspectable // Used for WinRT int countGuids = 0; foreach (var guidKey in guidToShadow.Keys) { if (guidKey != Utilities.GetGuidFromType(typeof(IInspectable)) && guidKey != Utilities.GetGuidFromType(typeof(IUnknown))) { countGuids++; } } guidPtr = Marshal.AllocHGlobal(Utilities.SizeOf <Guid>() * countGuids); Guids = new IntPtr[countGuids]; int i = 0; unsafe { var pGuid = (Guid *)guidPtr; foreach (var guidKey in guidToShadow.Keys) { if (guidKey == Utilities.GetGuidFromType(typeof(IInspectable)) || guidKey == Utilities.GetGuidFromType(typeof(IUnknown))) { continue; } pGuid[i] = guidKey; // Store the pointer Guids[i] = new IntPtr(pGuid + i); i++; } } }
public void DumpOnException(uint threadId, EXCEPTION_RECORD ev) { if (ev.ExceptionCode == BREAKPOINT_CODE) { return; } if (ev.ExceptionCode == CLRDBG_NOTIFICATION_EXCEPTION_CODE) { // based on https://social.msdn.microsoft.com/Forums/vstudio/en-US/bca092d4-d2b5-49ef-8bbc-cbce2c67aa89/net-40-firstchance-exception-0x04242420?forum=clr // it's a "notification exception" and can be safely ignored return; } if (ev.ExceptionCode == CTRL_C_EXCEPTION_CODE) { // we will also ignore CTRL+C events return; } // print information about the exception (decode it) ClrException managedException = null; foreach (var clrver in target.ClrVersions) { var runtime = clrver.CreateRuntime(); var thr = runtime.Threads.FirstOrDefault(t => t.OSThreadId == threadId); if (thr != null) { managedException = thr.CurrentException; break; } } var exceptionInfo = string.Format("{0:X}.{1} (\"{2}\")", ev.ExceptionCode, managedException != null ? managedException.Type.Name : "Native", managedException != null ? managedException.Message : "N/A"); PrintTrace("Exception: " + exceptionInfo); if (rgxFilter.IsMatch(exceptionInfo)) { byte[] threadContext = new byte[Native.CONTEXT_SIZE]; target.DataReader.GetThreadContext(threadId, 0, Native.CONTEXT_SIZE, threadContext); IntPtr pev = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(EXCEPTION_RECORD))); Marshal.StructureToPtr(new EXCEPTION_RECORD { ExceptionAddress = ev.ExceptionAddress, ExceptionFlags = ev.ExceptionFlags, ExceptionCode = ev.ExceptionCode, ExceptionRecord = IntPtr.Zero, NumberParameters = ev.NumberParameters, ExceptionInformation = ev.ExceptionInformation }, pev, false); var excpointers = new EXCEPTION_POINTERS { ExceptionRecord = pev, ContextRecord = threadContext }; IntPtr ptr = Marshal.AllocHGlobal(Marshal.SizeOf(excpointers)); Marshal.StructureToPtr(excpointers, ptr, false); var excinfo = new MINIDUMP_EXCEPTION_INFORMATION() { ThreadId = threadId, ClientPointers = false, ExceptionPointers = ptr }; var pexcinfo = Marshal.AllocHGlobal(Marshal.SizeOf(excinfo)); Marshal.StructureToPtr(excinfo, pexcinfo, false); MakeActualDump(pexcinfo); Marshal.FreeHGlobal(pev); Marshal.FreeHGlobal(pexcinfo); Marshal.FreeHGlobal(ptr); } }