public IList <RdcNeed> CreateNeedsList(SignatureInfo seedSignature, SignatureInfo sourceSignature, CancellationToken token) { var result = new List <RdcNeed>(); using (var seedStream = _seedSignatureRepository.GetContentForReading(seedSignature.Name)) using (var sourceStream = _sourceSignatureRepository.GetContentForReading(sourceSignature.Name)) { var fileReader = (IRdcFileReader) new RdcFileReader(seedStream); IRdcComparator comparator; if (_rdcLibrary.CreateComparator(fileReader, ComparatorBufferSize, out comparator) != 0) { throw new RdcException("Cannot create comparator"); } var inputBuffer = new RdcBufferPointer { Size = 0, Used = 0, Data = Marshal.AllocCoTaskMem(InputBufferSize + 16) }; var outputBuffer = Marshal.AllocCoTaskMem(Marshal.SizeOf(typeof(RdcNeed)) * 256); try { var eofInput = false; var eofOutput = false; var outputPointer = new RdcNeedPointer(); while (!eofOutput) { token.ThrowIfCancellationRequested(); if (inputBuffer.Size == inputBuffer.Used && !eofInput) { var bytesRead = 0; try { bytesRead = RdcBufferTools.IntPtrCopy(sourceStream, inputBuffer.Data, InputBufferSize); } catch (Exception ex) { throw new RdcException("Failed to read from the source stream.", ex); } inputBuffer.Size = (uint)bytesRead; inputBuffer.Used = 0; if (bytesRead < InputBufferSize) { eofInput = true; } } // Initialize our output needs array outputPointer.Size = 256; outputPointer.Used = 0; outputPointer.Data = outputBuffer; RdcError error; var hr = comparator.Process(eofInput, ref eofOutput, ref inputBuffer, ref outputPointer, out error); if (hr != 0) { throw new RdcException("Failed to process the signature block!", hr, error); } // Convert the stream to a Needs array. var needs = GetRdcNeedList(outputPointer); result.AddRange(needs); } } finally { // Free our resources if (outputBuffer != IntPtr.Zero) { Marshal.FreeCoTaskMem(outputBuffer); } if (inputBuffer.Data != IntPtr.Zero) { Marshal.FreeCoTaskMem(inputBuffer.Data); } } return(result); } }
private void CMB_videosources_SelectedIndexChanged(object sender, EventArgs e) { if (MainV2.MONO) { return; } int hr; int count; int size; object o; IBaseFilter capFilter = null; ICaptureGraphBuilder2 capGraph = null; AMMediaType media = null; VideoInfoHeader v; VideoStreamConfigCaps c; List <GCSBitmapInfo> modes = new List <GCSBitmapInfo>(); // Get the ICaptureGraphBuilder2 capGraph = (ICaptureGraphBuilder2) new CaptureGraphBuilder2(); IFilterGraph2 m_FilterGraph = (IFilterGraph2) new FilterGraph(); DsDevice[] capDevices; capDevices = DsDevice.GetDevicesOfCat(FilterCategory.VideoInputDevice); // Add the video device hr = m_FilterGraph.AddSourceFilterForMoniker(capDevices[CMB_videosources.SelectedIndex].Mon, null, "Video input", out capFilter); try { DsError.ThrowExceptionForHR(hr); } catch (Exception ex) { CustomMessageBox.Show("Can not add video source\n" + ex.ToString()); return; } // Find the stream config interface hr = capGraph.FindInterface(PinCategory.Capture, MediaType.Video, capFilter, typeof(IAMStreamConfig).GUID, out o); DsError.ThrowExceptionForHR(hr); IAMStreamConfig videoStreamConfig = o as IAMStreamConfig; if (videoStreamConfig == null) { throw new Exception("Failed to get IAMStreamConfig"); } hr = videoStreamConfig.GetNumberOfCapabilities(out count, out size); DsError.ThrowExceptionForHR(hr); IntPtr TaskMemPointer = Marshal.AllocCoTaskMem(size); for (int i = 0; i < count; i++) { IntPtr ptr = IntPtr.Zero; hr = videoStreamConfig.GetStreamCaps(i, out media, TaskMemPointer); v = (VideoInfoHeader)Marshal.PtrToStructure(media.formatPtr, typeof(VideoInfoHeader)); c = (VideoStreamConfigCaps)Marshal.PtrToStructure(TaskMemPointer, typeof(VideoStreamConfigCaps)); modes.Add(new GCSBitmapInfo(v.BmiHeader.Width, v.BmiHeader.Height, c.MaxFrameInterval, c.VideoStandard.ToString(), media)); } Marshal.FreeCoTaskMem(TaskMemPointer); DsUtils.FreeAMMediaType(media); CMB_videoresolutions.DataSource = modes; if (MainV2.getConfig("video_options") != "" && CMB_videosources.Text != "") { try { CMB_videoresolutions.SelectedIndex = int.Parse(MainV2.getConfig("video_options")); } catch { } // ignore bad entries } }
//色々サンプルを書きたいのよ private void Button_Click(object sender, RoutedEventArgs e) { try { this.hoge.ExplorerBrowserControl.Navigate((ShellObject)KnownFolders.Desktop); return; IntPtr PDesktop; Shell32Wrapper.SHGetDesktopFolder(out PDesktop); IShellFolder SHDesktop = (IShellFolder)Marshal.GetTypedObjectForIUnknown(PDesktop, typeof(IShellFolder)); IntPtr strr = Marshal.AllocCoTaskMem(Shell32Wrapper.MAX_PATH * 2 + 4); Marshal.WriteInt32(strr, 0, 0); IntPtr ptrPid; Shell32Wrapper.SHGetSpecialFolderLocation(IntPtr.Zero, (int)SpecialFolderID.CSIDL_DRIVES, out ptrPid); //なんかDesktop自身の名前は取得方法がわからん //if (SHDesktop.GetDisplayNameOf(desktop, SHGNO.NORMAL, strr) == Shell32Wrapper.S_OK) if (SHDesktop.GetDisplayNameOf(ptrPid, SHGNO.NORMAL, strr) == Shell32Wrapper.S_OK) { StringBuilder buf = new StringBuilder(Shell32Wrapper.MAX_PATH); ShlwapiWrapper.StrRetToBuf(strr, PDesktop, buf, Shell32Wrapper.MAX_PATH); MessageBox.Show(buf.ToString()); } Marshal.FreeCoTaskMem(strr); //対象ファイルの親のシェルフォルダの PIDL を取得する IntPtr PFolder; uint fcharcnt = 0; SFGAO fattr = SFGAO.BROWSABLE; if (SHDesktop.ParseDisplayName(IntPtr.Zero, IntPtr.Zero, @"C:\temp", ref fcharcnt, out PFolder, ref fattr) == Shell32Wrapper.S_OK) { //対象ファイルの親のシェルフォルダのポインタを取得する IntPtr PPV; if (SHDesktop.BindToObject(PFolder, IntPtr.Zero, GUIDs.IID_IShellFolder, out PPV) == Shell32Wrapper.S_OK) { //対象ファイルの親のシェルフォルダ IShellFolder を取得する IShellFolder SHFolder = (IShellFolder)Marshal.GetTypedObjectForIUnknown(PPV, typeof(IShellFolder)); //対象ファイルの PIDL (親のシェルフォルダからの相対 PIDL)を取得する IntPtr PFile; if (SHFolder.ParseDisplayName(IntPtr.Zero, IntPtr.Zero, "a.vbs", ref fcharcnt, out PFile, ref fattr) == Shell32Wrapper.S_OK) { //対象ファイルの IContextMenu へのポインタを取得する IntPtr[] children = new IntPtr[] { PFile }; IntPtr PContext; if (SHFolder.GetUIObjectOf(IntPtr.Zero, (uint)children.Length, children, GUIDs.IID_IContextMenu, IntPtr.Zero, out PContext) == Shell32Wrapper.S_OK) { //対象ファイルの IContextMenu を取得する IContextMenu CContext = (IContextMenu)Marshal.GetTypedObjectForIUnknown(PContext, typeof(IContextMenu)); //対象ファイルの IContextMenu2, IContextMenu3 のポインタを取得する IntPtr PContext2, PContext3; Marshal.QueryInterface(PContext, ref GUIDs.IID_IContextMenu2, out PContext2); Marshal.QueryInterface(PContext, ref GUIDs.IID_IContextMenu3, out PContext3); IContextMenu2 CContext2 = (IContextMenu2)Marshal.GetTypedObjectForIUnknown(PContext2, typeof(IContextMenu2)); IContextMenu3 CContext3 = (IContextMenu3)Marshal.GetTypedObjectForIUnknown(PContext3, typeof(IContextMenu3)); //ポップアップメニューを作成する IntPtr PPopup = User32Wrapper.CreatePopupMenu(); //ポップアップメニューに、コンテキストメニュー IContextMenu を追加する CMF ContextMenuFlag = CMF.EXPLORE | CMF.CANRENAME; CContext.QueryContextMenu(PPopup, 0, Shell32Wrapper.CMD_FIRST, Shell32Wrapper.CMD_LAST, ContextMenuFlag); //ポップアップメニューを表示する //呼び出しをブロックします uint selected = User32Wrapper.TrackPopupMenuEx(PPopup, TPM.RETURNCMD, 0, 0, new System.Windows.Interop.WindowInteropHelper(this).Handle, IntPtr.Zero); if (selected >= Shell32Wrapper.CMD_FIRST) { uint cmdidx = selected - Shell32Wrapper.CMD_FIRST; Helper.InvokeCommand(CContext, cmdidx, @"C:\temp", new Point(0, 0)); } User32Wrapper.DestroyMenu(PPopup); Marshal.ReleaseComObject(CContext3); Marshal.ReleaseComObject(CContext2); Marshal.Release(PContext3); Marshal.Release(PContext2); Marshal.ReleaseComObject(CContext); } Marshal.Release(PContext); } Marshal.FreeCoTaskMem(PFile); Marshal.ReleaseComObject(SHFolder); } Marshal.Release(PPV); } //なんでかExceptionが発生するのでコメントアウト ← 解放するメソッドを間違えていた //Marshal.Release(PIDLParent); Marshal.FreeCoTaskMem(PFolder); Marshal.ReleaseComObject(SHDesktop); Marshal.Release(PDesktop); } catch (Exception ex) { MessageBox.Show(ex.Message, ex.GetType().Name, MessageBoxButton.OK, MessageBoxImage.Error); } }
/**/ /// <summary> /// 删除已经存在的自定义纸张 /// </summary> /// <param name="PrinterName">打印机名称</param> /// <param name="PaperName">纸张名称</param> public static void DeleteCustomPaperSize(string PrinterName, string PaperName) { const int PRINTER_ACCESS_USE = 0x00000008; const int PRINTER_ACCESS_ADMINISTER = 0x00000004; structPrinterDefaults defaults = new structPrinterDefaults(); defaults.pDatatype = null; defaults.pDevMode = IntPtr.Zero; defaults.DesiredAccess = PRINTER_ACCESS_ADMINISTER | PRINTER_ACCESS_USE; IntPtr hPrinter = IntPtr.Zero; //打开打印机 if (OpenPrinter(PrinterName, out hPrinter, ref defaults)) { try { DeleteForm(hPrinter, PaperName); ClosePrinter(hPrinter); } catch { } } } #endregion 除已经存在的自定义纸张 #region 指定的打印机设置以mm为单位的自定义纸张(Form) /**/ /// <summary> /// 指定的打印机设置以mm为单位的自定义纸张(Form) /// </summary> /// <param name="PrinterName">打印机名称</param> /// <param name="PaperName">Form名称</param> /// <param name="WidthInMm">以mm为单位的宽度</param> /// <param name="HeightInMm">以mm为单位的高度</param> public static void AddCustomPaperSize(string PrinterName, string PaperName, float WidthInMm, float HeightInMm) { if (PlatformID.Win32NT == Environment.OSVersion.Platform) { const int PRINTER_ACCESS_USE = 0x00000008; const int PRINTER_ACCESS_ADMINISTER = 0x00000004; structPrinterDefaults defaults = new structPrinterDefaults(); defaults.pDatatype = null; defaults.pDevMode = IntPtr.Zero; defaults.DesiredAccess = PRINTER_ACCESS_ADMINISTER | PRINTER_ACCESS_USE; IntPtr hPrinter = IntPtr.Zero; //打开打印机 if (OpenPrinter(PrinterName, out hPrinter, ref defaults)) { try { //如果Form存在删除之 DeleteForm(hPrinter, PaperName); //创建并初始化FORM_INFO_1 FormInfo1 formInfo = new FormInfo1(); formInfo.Flags = 0; formInfo.pName = PaperName; formInfo.Size.width = (int)(WidthInMm * 1000.0); formInfo.Size.height = (int)(HeightInMm * 1000.0); formInfo.ImageableArea.left = 0; formInfo.ImageableArea.right = formInfo.Size.width; formInfo.ImageableArea.top = 0; formInfo.ImageableArea.bottom = formInfo.Size.height; if (!AddForm(hPrinter, 1, ref formInfo)) { StringBuilder strBuilder = new StringBuilder(); strBuilder.AppendFormat("向打印机 {1} 添加自定义纸张 {0} 失败!错误代号:{2}", PaperName, PrinterName, GetLastError()); throw new ApplicationException(strBuilder.ToString()); } //初始化 const int DM_OUT_BUFFER = 2; const int DM_IN_BUFFER = 8; structDevMode devMode = new structDevMode(); IntPtr hPrinterInfo, hDummy; PRINTER_INFO_9 printerInfo; printerInfo.pDevMode = IntPtr.Zero; int iPrinterInfoSize, iDummyInt; int iDevModeSize = DocumentProperties(IntPtr.Zero, hPrinter, PrinterName, IntPtr.Zero, IntPtr.Zero, 0); if (iDevModeSize < 0) { throw new ApplicationException("无法取得DEVMODE结构的大小!"); } //分配缓冲 IntPtr hDevMode = Marshal.AllocCoTaskMem(iDevModeSize + 100); //获取DEV_MODE指针 int iRet = DocumentProperties(IntPtr.Zero, hPrinter, PrinterName, hDevMode, IntPtr.Zero, DM_OUT_BUFFER); if (iRet < 0) { throw new ApplicationException("无法获得DEVMODE结构!"); } //填充DEV_MODE devMode = (structDevMode)Marshal.PtrToStructure(hDevMode, devMode.GetType()); devMode.dmFields = 0x10000; //FORM名称 devMode.dmFormName = PaperName; Marshal.StructureToPtr(devMode, hDevMode, true); iRet = DocumentProperties(IntPtr.Zero, hPrinter, PrinterName, printerInfo.pDevMode, printerInfo.pDevMode, DM_IN_BUFFER | DM_OUT_BUFFER); if (iRet < 0) { throw new ApplicationException("无法为打印机设定打印方向!"); } GetPrinter(hPrinter, 9, IntPtr.Zero, 0, out iPrinterInfoSize); if (iPrinterInfoSize == 0) { throw new ApplicationException("调用GetPrinter方法失败!"); } hPrinterInfo = Marshal.AllocCoTaskMem(iPrinterInfoSize + 100); bool bSuccess = GetPrinter(hPrinter, 9, hPrinterInfo, iPrinterInfoSize, out iDummyInt); if (!bSuccess) { throw new ApplicationException("调用GetPrinter方法失败!"); } printerInfo = (PRINTER_INFO_9)Marshal.PtrToStructure(hPrinterInfo, printerInfo.GetType()); printerInfo.pDevMode = hDevMode; Marshal.StructureToPtr(printerInfo, hPrinterInfo, true); bSuccess = SetPrinter(hPrinter, 9, hPrinterInfo, 0); if (!bSuccess) { throw new Win32Exception(Marshal.GetLastWin32Error(), "调用SetPrinter方法失败,无法进行打印机设置!"); } SendMessageTimeout( new IntPtr(HWND_BROADCAST), WM_SETTINGCHANGE, IntPtr.Zero, IntPtr.Zero, PrinterHelper.SendMessageTimeoutFlags.SMTO_NORMAL, 1000, out hDummy); } finally { ClosePrinter(hPrinter); } } else { StringBuilder strBuilder = new StringBuilder(); strBuilder.AppendFormat("无法打开打印机{0}, 错误代号: {1}", PrinterName, GetLastError()); throw new ApplicationException(strBuilder.ToString()); } } else { structDevMode pDevMode = new structDevMode(); IntPtr hDC = CreateDC(null, PrinterName, null, ref pDevMode); if (hDC != IntPtr.Zero) { const long DM_PAPERSIZE = 0x00000002L; const long DM_PAPERLENGTH = 0x00000004L; const long DM_PAPERWIDTH = 0x00000008L; pDevMode.dmFields = (int)(DM_PAPERSIZE | DM_PAPERWIDTH | DM_PAPERLENGTH); pDevMode.dmPaperSize = 256; pDevMode.dmPaperWidth = (short)(WidthInMm * 1000.0); pDevMode.dmPaperLength = (short)(HeightInMm * 1000.0); ResetDC(hDC, ref pDevMode); DeleteDC(hDC); } } }
public void StartRunning() { // m_selectedDevice.VideoFrameCompleted += new DeckLinkVideoOutputHandler((b) => this.BeginInvoke((Action)(() => { ScheduleNextFrame(b); }))); m_selectedDevice.AudioOutputRequested += new DeckLinkAudioOutputHandler(() => this.BeginInvoke((Action)(() => { WriteNextAudioSamples(); }))); m_selectedDevice.PlaybackStopped += new DeckLinkPlaybackStoppedHandler(() => this.BeginInvoke((Action)(() => { DisableOutput(); }))); m_audioChannelCount = 16; m_audioSampleDepth = _BMDAudioSampleType.bmdAudioSampleType16bitInteger; m_audioSampleRate = _BMDAudioSampleRate.bmdAudioSampleRate48kHz; // //- Extract the IDeckLinkDisplayMode from the display mode popup menu IDeckLinkDisplayMode videoDisplayMode; videoDisplayMode = ((DisplayModeEntry)comboBoxVideoFormat.SelectedItem).displayMode; m_frameWidth = videoDisplayMode.GetWidth(); m_frameHeight = videoDisplayMode.GetHeight(); videoDisplayMode.GetFrameRate(out m_frameDuration, out m_frameTimescale); // Calculate the number of frames per second, rounded up to the nearest integer. For example, for NTSC (29.97 FPS), framesPerSecond == 30. m_framesPerSecond = (uint)((m_frameTimescale + (m_frameDuration - 1)) / m_frameDuration); var mode = videoDisplayMode.GetDisplayMode(); // Set the video output mode m_selectedDevice.deckLinkOutput.EnableVideoOutput(videoDisplayMode.GetDisplayMode(), _BMDVideoOutputFlags.bmdVideoOutputFlagDefault); // Set the audio output mode m_selectedDevice.deckLinkOutput.EnableAudioOutput(m_audioSampleRate, m_audioSampleDepth, m_audioChannelCount, _BMDAudioOutputStreamType.bmdAudioOutputStreamContinuous); // Generate one second of audio m_audioBufferSampleLength = (uint)(m_framesPerSecond * audioSamplesPerFrame()); int m_audioBufferDataLength = (int)(m_audioBufferSampleLength * audioDataPerSample()); m_audioBuffer = Marshal.AllocCoTaskMem(m_audioBufferDataLength); m_audioBufferAllocated = true; lock (m_selectedDevice) { // Zero the buffer (interpreted as audio silence) for (int i = 0; i < m_audioBufferDataLength; i++) { Marshal.WriteInt32(m_audioBuffer, i, 0); } FillSine(new IntPtr(m_audioBuffer.ToInt64()), m_audioBufferSampleLength, m_audioChannelCount, m_audioSampleDepth); m_audioBufferReadOffset = 0; m_audioBufferWriteOffset = 0; } m_videoFrameARGBBars = CreateOutputVideoFrame(FillBGRAColourBars, _BMDPixelFormat.bmdFormat8BitARGB); m_videoFrame = CreateOutputVideoFrame(FillARGBColourBars, _BMDPixelFormat.bmdFormat8BitARGB); m_videoFrameBars = CreateOutputVideoFrame(FillColourBars); m_pixelFormat = _BMDPixelFormat.bmdFormat8BitBGRA; m_videoFrameBGRA = CreateOutputVideoFrame(FillColourBars); m_videoFrameBGRABars = CreateOutputVideoFrame(FillBGRAColourBars, _BMDPixelFormat.bmdFormat8BitBGRA); m_pixelFormat = _BMDPixelFormat.bmdFormat8BitARGB; m_running = true; buttonStartStop.Text = "Stop"; // Begin video preroll by scheduling a second of frames in hardware m_totalFramesScheduled = 0; for (uint i = 0; i < m_prerollFrames; i++) { ScheduleNextFrame(true); } // Begin audio preroll. This will begin calling our audio callback, which will then start the DeckLink output stream - StartScheduledPlayback. m_selectedDevice.deckLinkOutput.BeginAudioPreroll(); // StopRunning(); }
/// <summary> /// Gets the control details /// </summary> protected void GetControlDetails() { mixerControlDetails.cbStruct = Marshal.SizeOf(mixerControlDetails); mixerControlDetails.dwControlID = mixerControl.dwControlID; if (IsCustom) { mixerControlDetails.cChannels = 0; } else if ((mixerControl.fdwControl & MixerInterop.MIXERCONTROL_CONTROLF_UNIFORM) != 0) { mixerControlDetails.cChannels = 1; } else { mixerControlDetails.cChannels = nChannels; } if ((mixerControl.fdwControl & MixerInterop.MIXERCONTROL_CONTROLF_MULTIPLE) != 0) { mixerControlDetails.hwndOwner = (IntPtr)mixerControl.cMultipleItems; } else if (IsCustom) { mixerControlDetails.hwndOwner = IntPtr.Zero; // TODO: special cases } else { mixerControlDetails.hwndOwner = IntPtr.Zero; } if (IsBoolean) { mixerControlDetails.cbDetails = Marshal.SizeOf(new MixerInterop.MIXERCONTROLDETAILS_BOOLEAN()); } else if (IsListText) { mixerControlDetails.cbDetails = Marshal.SizeOf(new MixerInterop.MIXERCONTROLDETAILS_LISTTEXT()); } else if (IsSigned) { mixerControlDetails.cbDetails = Marshal.SizeOf(new MixerInterop.MIXERCONTROLDETAILS_SIGNED()); } else if (IsUnsigned) { mixerControlDetails.cbDetails = Marshal.SizeOf(new MixerInterop.MIXERCONTROLDETAILS_UNSIGNED()); } else { // must be custom mixerControlDetails.cbDetails = mixerControl.Metrics.customData; } var detailsSize = mixerControlDetails.cbDetails * mixerControlDetails.cChannels; if ((mixerControl.fdwControl & MixerInterop.MIXERCONTROL_CONTROLF_MULTIPLE) != 0) { // fixing issue 16390 - calculating size correctly for multiple items detailsSize *= (int)mixerControl.cMultipleItems; } IntPtr buffer = Marshal.AllocCoTaskMem(detailsSize); // To copy stuff in: // Marshal.StructureToPtr( theStruct, buffer, false ); mixerControlDetails.paDetails = buffer; MmResult err = MixerInterop.mixerGetControlDetails(mixerHandle, ref mixerControlDetails, MixerFlags.Value | mixerHandleType); // let the derived classes get the details before we free the handle if (err == MmResult.NoError) { GetDetails(mixerControlDetails.paDetails); } Marshal.FreeCoTaskMem(buffer); if (err != MmResult.NoError) { throw new MmException(err, "mixerGetControlDetails"); } }
/// <summary> /// Installs and optionally starts the service. /// </summary> /// <param name="path">The full path of the service exe.</param> /// <param name="name">The name of the service.</param> /// <param name="displayName">The display name of the service.</param> /// <param name="description">The description for the service.</param> /// <param name="startMode">The service start mode.</param> /// <param name="userName">The account name. Null to use the default account (LocalSystem).</param> /// <param name="password">The account password.</param> /// <param name="start">True to start the service after the installation; otherwise, false. /// Once the method returns you can use this parameter to check whether the service is running or not.</param> /// <param name="dependencies">The list of dependencies services. Null if there are no dependencies.</param> /// <returns>True for success. Otherwise, false.</returns> public static bool InstallService( string path, string name, string displayName, string description, StartMode startMode, string userName, string password, ref bool start, string[] dependencies) { uint SC_MANAGER_CREATE_SERVICE = 0x0002; if (string.IsNullOrEmpty(userName)) { userName = null; password = null; } // check if an existing service needs to uninstalled. try { Service existingService = ServiceManager.GetService(name); if (existingService != null) { if (existingService.StartMode != StartMode.Disabled && existingService.Path == path) { if (existingService.Status == ServiceStatus.Stopped) { ServiceManager.StartService(name); } return(true); } UnInstallService(name); } } catch (Exception e) { Utils.Trace(e, "CreateService Exception"); } IntPtr svHandle = IntPtr.Zero; try { IntPtr scHandle = OpenSCManagerW(null, null, SC_MANAGER_CREATE_SERVICE); if (scHandle.ToInt64() != 0) { string dependencyServices = string.Empty; if (dependencies != null && dependencies.Length > 0) { for (int i = 0; i < dependencies.Length; i++) { if (!string.IsNullOrEmpty(dependencies[i])) { dependencyServices += dependencies[i].Trim(); if (i < dependencies.Length - 1) { dependencyServices += "\0";//add a null char separator } } } } if (dependencyServices == string.Empty) { dependencyServices = null; } // lpDependencies, if not null, must be a series of strings concatenated with the null character as a delimiter, including a trailing one. svHandle = CreateServiceW( scHandle, name, displayName, (uint)ServiceAccess.AllAccess, (uint)ServiceType.OwnProcess, (uint)startMode, (uint)ServiceError.ErrorNormal, path, null, 0, dependencyServices, userName, password); if (svHandle.ToInt64() == 0) { int error = GetLastError(); Utils.Trace("CreateService Error: {0}", error); return(false); } // set the description. if (!String.IsNullOrEmpty(description)) { SERVICE_DESCRIPTION info = new SERVICE_DESCRIPTION(); info.lpDescription = description; IntPtr pInfo = Marshal.AllocCoTaskMem(Marshal.SizeOf(typeof(SERVICE_DESCRIPTION))); Marshal.StructureToPtr(info, pInfo, false); try { int result = ChangeServiceConfig2W(svHandle, SERVICE_CONFIG_DESCRIPTION, pInfo); if (result == 0) { Utils.Trace("Could not set description for service: {0}", displayName); } } finally { Marshal.DestroyStructure(pInfo, typeof(SERVICE_DESCRIPTION)); Marshal.FreeCoTaskMem(pInfo); } } // start the service. if (start) { start = ServiceManager.StartService(name, new TimeSpan(0, 0, 0, 60)); } return(true); } } catch (Exception e) { Utils.Trace(e, "CreateService Exception"); } finally { SafeCloseServiceHandle(svHandle); } return(false); }
public static string BrowseForDirectory( IntPtr owner, string initialDirectory = null, string title = null ) { IVsUIShell uiShell = GetService(typeof(SVsUIShell)) as IVsUIShell; if (null == uiShell) { using (var ofd = new FolderBrowserDialog()) { ofd.RootFolder = Environment.SpecialFolder.Desktop; ofd.SelectedPath = initialDirectory; ofd.ShowNewFolderButton = false; DialogResult result; if (owner == IntPtr.Zero) { result = ofd.ShowDialog(); } else { result = ofd.ShowDialog(NativeWindow.FromHandle(owner)); } if (result == DialogResult.OK) { return(ofd.SelectedPath); } else { return(null); } } } if (owner == IntPtr.Zero) { ErrorHandler.ThrowOnFailure(uiShell.GetDialogOwnerHwnd(out owner)); } VSBROWSEINFOW[] browseInfo = new VSBROWSEINFOW[1]; browseInfo[0].lStructSize = (uint)Marshal.SizeOf(typeof(VSBROWSEINFOW)); browseInfo[0].pwzInitialDir = initialDirectory; browseInfo[0].pwzDlgTitle = title; browseInfo[0].hwndOwner = owner; browseInfo[0].nMaxDirName = 260; IntPtr pDirName = IntPtr.Zero; try { browseInfo[0].pwzDirName = pDirName = Marshal.AllocCoTaskMem(520); int hr = uiShell.GetDirectoryViaBrowseDlg(browseInfo); if (hr == VSConstants.OLE_E_PROMPTSAVECANCELLED) { return(null); } ErrorHandler.ThrowOnFailure(hr); return(Marshal.PtrToStringAuto(browseInfo[0].pwzDirName)); } finally { if (pDirName != IntPtr.Zero) { Marshal.FreeCoTaskMem(pDirName); } } }
private static List <Icon> GetIconInfo() { List <Icon> aIcons = new List <Icon>(); //取桌面ListView句柄 IntPtr hDeskTop = WinAPI.FindWindow("progman", null); hDeskTop = WinAPI.FindWindowEx(hDeskTop, IntPtr.Zero, "shelldll_defview", null); hDeskTop = WinAPI.FindWindowEx(hDeskTop, IntPtr.Zero, "syslistview32", null); //取explorer.exe句柄 int dwProcessId; WinAPI.GetWindowThreadProcessId(hDeskTop, out dwProcessId); IntPtr hProcess = WinAPI.OpenProcess(WinAPI.PROCESS_VM_OPERATION | WinAPI.PROCESS_VM_READ | WinAPI.PROCESS_VM_WRITE, false, dwProcessId); unsafe { //在 explorer.exe 空间内分配内存 IntPtr pv = WinAPI.VirtualAllocEx(hProcess, IntPtr.Zero, sizeof(Point), WinAPI.MEM_COMMIT, WinAPI.PAGE_READWRITE); IntPtr pn = WinAPI.VirtualAllocEx(hProcess, IntPtr.Zero, WinAPI.MAX_PATH * 2, WinAPI.MEM_COMMIT, WinAPI.PAGE_READWRITE); IntPtr plvitem = WinAPI.VirtualAllocEx(hProcess, IntPtr.Zero, WinAPI.GetLvItemSize(), WinAPI.MEM_COMMIT, WinAPI.PAGE_READWRITE); //发送获取坐标消息 int count = WinAPI.ListView_GetItemCount(hDeskTop); for (int i = 0; i < count; i++) { Icon icon = new Icon(); WinAPI.ListView_GetItemText(hDeskTop, i, hProcess, plvitem, (int)pn, WinAPI.MAX_PATH * 2); WinAPI.ListView_GetItemPosition(hDeskTop, i, pv); //读取坐标数据 int lpNumberOfBytesRead; WinAPI.ReadProcessMemory(hProcess, pv, out icon.Position, sizeof(Point), out lpNumberOfBytesRead); //读取文本数据 IntPtr pszName = Marshal.AllocCoTaskMem(WinAPI.MAX_PATH * 2); WinAPI.ReadProcessMemory(hProcess, pn, pszName, WinAPI.MAX_PATH * 2, out lpNumberOfBytesRead); icon.Text = Marshal.PtrToStringUni(pszName); Marshal.FreeCoTaskMem(pszName); //加入列表 aIcons.Add(icon); Console.Out.WriteLine(icon.Text); //int result = Marshal.GetLastWin32Error(); } //释放内存 WinAPI.VirtualFreeEx(hProcess, pv, sizeof(Point), 0); WinAPI.VirtualFreeEx(hProcess, pn, WinAPI.MAX_PATH * 2, 0); WinAPI.VirtualFreeEx(hProcess, plvitem, WinAPI.GetLvItemSize(), 0); //释放句柄 WinAPI.CloseHandle(hProcess); } return(aIcons); }
public void SetMediaItem(IResourceLocator locator, string mediaItemTitle, MediaItem mediaItem) { _mediaItem = mediaItem; // free previous opened resource FilterGraphTools.TryDispose(ref _resourceAccessor); FilterGraphTools.TryDispose(ref _rot); _state = PlayerState.Active; _isPaused = true; try { _resourceLocator = locator; _mediaItemTitle = mediaItemTitle; CreateResourceAccessor(); // Create a DirectShow FilterGraph CreateGraphBuilder(); // Add it in ROT (Running Object Table) for debug purpose, it allows to view the Graph from outside (i.e. graphedit) _rot = new DsROTEntry(_graphBuilder); // Add a notification handler (see WndProc) _instancePtr = Marshal.AllocCoTaskMem(4); IMediaEventEx mee = _graphBuilder as IMediaEventEx; if (mee != null) { mee.SetNotifyWindow(SkinContext.Form.Handle, WM_GRAPHNOTIFY, _instancePtr); } // Create the Allocator / Presenter object AddPresenter(); ServiceRegistration.Get <ILogger>().Debug("{0}: Adding audio renderer", PlayerTitle); AddAudioRenderer(); ServiceRegistration.Get <ILogger>().Debug("{0}: Adding preferred codecs", PlayerTitle); AddPreferredCodecs(); ServiceRegistration.Get <ILogger>().Debug("{0}: Adding source filter", PlayerTitle); AddSourceFilter(); ServiceRegistration.Get <ILogger>().Debug("{0}: Adding subtitle filter", PlayerTitle); AddSubtitleFilter(true); ServiceRegistration.Get <ILogger>().Debug("{0}: Run graph", PlayerTitle); //This needs to be done here before we check if the evr pins are connected //since this method gives players the chance to render the last bits of the graph OnBeforeGraphRunning(); // Now run the graph, i.e. the DVD player needs a running graph before getting informations from dvd filter. IMediaControl mc = (IMediaControl)_graphBuilder; int hr = mc.Run(); new HRESULT(hr).Throw(); _initialized = true; OnGraphRunning(); } catch (Exception) { Shutdown(); throw; } }
public void Generate(string inputFilePath, string inputFileContents, string defaultNamespace, out IntPtr outputFileContents, out int output, IVsGeneratorProgress generateProgress) { try { if (cancelGenerating) { byte[] fileData = File.ReadAllBytes(Path.ChangeExtension(inputFilePath, GetDefaultExtension())); // Return our summary data, so that Visual Studio may write it to disk. outputFileContents = Marshal.AllocCoTaskMem(fileData.Length); Marshal.Copy(fileData, 0, outputFileContents, fileData.Length); output = fileData.Length; return; } this.inputFileContents = inputFileContents; this.inputFilePath = inputFilePath; this.defaultNamespace = defaultNamespace; int iFound = 0; uint itemId = 0; ProjectItem projectItem; Microsoft.VisualStudio.Shell.Interop.VSDOCUMENTPRIORITY[] pdwPriority = new Microsoft.VisualStudio.Shell.Interop.VSDOCUMENTPRIORITY[1]; // Obtain a reference to the current project as an IVsProject type Microsoft.VisualStudio.Shell.Interop.IVsProject VsProject = VsHelper.ToVsProject(project); // This locates, and returns a handle to our source file, as a ProjectItem VsProject.IsDocumentInProject(InputFilePath, out iFound, pdwPriority, out itemId); // If our source file was found in the project (which it should have been) if (iFound != 0 && itemId != 0) { Microsoft.VisualStudio.OLE.Interop.IServiceProvider oleSp = null; VsProject.GetItemContext(itemId, out oleSp); if (oleSp != null) { ServiceProvider sp = new ServiceProvider(oleSp); // Convert our handle to a ProjectItem projectItem = sp.GetService(typeof(ProjectItem)) as ProjectItem; } else { throw new ApplicationException("Unable to retrieve Visual Studio ProjectItem"); } } else { throw new ApplicationException("Unable to retrieve Visual Studio ProjectItem"); } oldFileNames.Clear(); newFileNames.Clear(); foreach (ProjectItem childItem in projectItem.ProjectItems) { oldFileNames.Add(childItem.Name); if (!childItem.Name.EndsWith(".cs")) { childItem.Properties.Item("BuildAction").Value = 0; } } // Now we can start our work, iterate across all the 'items' in our source file foreach (T item in this) { // Obtain a name for this target file string fileName = GetFileName(item); // Add it to the tracking cache newFileNames.Add(fileName); // Fully qualify the file on the filesystem string filePath = Path.Combine(Path.GetDirectoryName(inputFilePath), fileName); if (!(item as IChangable).IsChanged && File.Exists(filePath)) { continue; } try { bool isNewAdded = !oldFileNames.Contains(fileName); if (!isNewAdded) { // Check out this file. if (project.DTE.SourceControl.IsItemUnderSCC(filePath) && !project.DTE.SourceControl.IsItemCheckedOut(filePath)) { project.DTE.SourceControl.CheckOutItem(filePath); } } // Create the file FileStream fs = File.Create(filePath); try { // Generate our target file content byte[] data = GenerateContent(item); // Write it out to the stream fs.Write(data, 0, data.Length); fs.Close(); OnFileGenerated(filePath, isNewAdded); /* * Here you may wish to perform some addition logic * such as, setting a custom tool for the target file if it * is intented to perform its own generation process. * Or, set the target file as an 'Embedded Resource' so that * it is embedded into the final Assembly. * * EnvDTE.Property prop = itm.Properties.Item("CustomTool"); * * if (String.IsNullOrEmpty((string)prop.Value) || !String.Equals((string)prop.Value, typeof(AnotherCustomTool).Name)) * { * prop.Value = typeof(AnotherCustomTool).Name; * } */ } catch (Exception ex) { fs.Close(); OnError(ex); LogException(ex); } } catch (Exception ex) { throw ex; } } // Perform some clean-up, making sure we delete any old (stale) target-files foreach (ProjectItem childItem in projectItem.ProjectItems) { if (!(childItem.Name.EndsWith(GetDefaultExtension()) || newFileNames.Contains(childItem.Name))) { // Then delete it childItem.Delete(); } } foreach (var newFileName in newFileNames) { if (!oldFileNames.Contains(newFileName)) { string fileName = Path.Combine(inputFilePath.Substring(0, inputFilePath.LastIndexOf(Path.DirectorySeparatorChar)), newFileName); // Add the newly generated file to the solution, as a child of the source file... ProjectItem itm = projectItem.ProjectItems.AddFromFile(fileName); // Set buildaction to none if (!newFileName.EndsWith(".cs")) { itm.Properties.Item("BuildAction").Value = 0; } } } // Generate our summary content for our 'single' file byte[] summaryData = GenerateSummaryContent(); if (summaryData == null) { outputFileContents = IntPtr.Zero; output = 0; } else { // Return our summary data, so that Visual Studio may write it to disk. outputFileContents = Marshal.AllocCoTaskMem(summaryData.Length); Marshal.Copy(summaryData, 0, outputFileContents, summaryData.Length); output = summaryData.Length; } } catch (Exception ex) { OnError(ex); LogException(ex); outputFileContents = IntPtr.Zero; output = 0; } }
internal int ReadStruct(byte[] b, int Offset) { uint method = 10; this.TrEntry(method, new object[] { b, Offset }); short num2 = BitConverter.ToInt16(b, Offset + 20); int cb = 0; IntPtr zero = IntPtr.Zero; int result = 0; try { if (num2 != 0) { cb = Marshal.SizeOf(new structMQASYNC_MESSAGE_SEG1()); zero = Marshal.AllocCoTaskMem(cb); Marshal.Copy(b, Offset, zero, cb); structMQASYNC_MESSAGE_SEG1 tmqasync_message_seg = (structMQASYNC_MESSAGE_SEG1)Marshal.PtrToStructure(zero, typeof(structMQASYNC_MESSAGE_SEG1)); this.asyncMsg.version = tmqasync_message_seg.version; this.asyncMsg.hObj = tmqasync_message_seg.hObj; this.asyncMsg.messageIndex = tmqasync_message_seg.messageIndex; this.asyncMsg.globalMessageIndex = tmqasync_message_seg.globalMessageIndex; this.asyncMsg.segmentLength = tmqasync_message_seg.segmentLength; this.asyncMsg.segmentIndex = tmqasync_message_seg.segmentIndex; this.asyncMsg.selectionIndex = tmqasync_message_seg.selectionIndex; this.asyncMsg.reasonCode = 0; this.asyncMsg.status = 0; this.asyncMsg.totalMsgLength = 0; this.asyncMsg.actualMsgLength = 0; this.asyncMsg.msgToken = null; this.asyncMsg.resolvedQNameLen = 0; Marshal.FreeCoTaskMem(zero); return(cb + Offset); } cb = Marshal.SizeOf(this.asyncMsg); zero = Marshal.AllocCoTaskMem(cb); Marshal.Copy(b, Offset, zero, cb); this.asyncMsg = (structMQASYNC_MESSAGE)Marshal.PtrToStructure(zero, typeof(structMQASYNC_MESSAGE)); int resolvedQNameLen = this.asyncMsg.resolvedQNameLen; int index = Offset + 0x37; if (resolvedQNameLen != 0) { if (resolvedQNameLen < 0x30) { this.resolvedQName = Encoding.ASCII.GetString(b, index, resolvedQNameLen - 1); } else { this.resolvedQName = Encoding.ASCII.GetString(b, index, resolvedQNameLen); } } index += ((resolvedQNameLen + 2) & -4) + 1; result = this.msgDescriptor.ReadStruct(b, index); Marshal.FreeCoTaskMem(zero); } finally { base.TrExit(method, result); } return(result); }
public OutputArgument() : base(Marshal.AllocCoTaskMem(24)) { }
private static IntPtr BytesToIntPtr(byte[] bytes) { return(Marshal.AllocCoTaskMem(bytes.Length)); }
public static string BrowseForFileOpen(this IServiceProvider serviceProvider, IntPtr owner, string filter, string initialPath = null) { if (string.IsNullOrEmpty(initialPath)) { initialPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal) + Path.DirectorySeparatorChar; } IVsUIShell uiShell = serviceProvider.GetService(typeof(SVsUIShell)) as IVsUIShell; if (null == uiShell) { using (var sfd = new System.Windows.Forms.OpenFileDialog()) { sfd.AutoUpgradeEnabled = true; sfd.Filter = filter; sfd.FileName = Path.GetFileName(initialPath); sfd.InitialDirectory = Path.GetDirectoryName(initialPath); DialogResult result; if (owner == IntPtr.Zero) { result = sfd.ShowDialog(); } else { result = sfd.ShowDialog(NativeWindow.FromHandle(owner)); } if (result == DialogResult.OK) { return(sfd.FileName); } else { return(null); } } } if (owner == IntPtr.Zero) { ErrorHandler.ThrowOnFailure(uiShell.GetDialogOwnerHwnd(out owner)); } VSOPENFILENAMEW[] openInfo = new VSOPENFILENAMEW[1]; openInfo[0].lStructSize = (uint)Marshal.SizeOf(typeof(VSOPENFILENAMEW)); openInfo[0].pwzFilter = filter.Replace('|', '\0') + "\0"; openInfo[0].hwndOwner = owner; openInfo[0].nMaxFileName = 260; var pFileName = Marshal.AllocCoTaskMem(520); openInfo[0].pwzFileName = pFileName; openInfo[0].pwzInitialDir = Path.GetDirectoryName(initialPath); var nameArray = (Path.GetFileName(initialPath) + "\0").ToCharArray(); Marshal.Copy(nameArray, 0, pFileName, nameArray.Length); try { int hr = uiShell.GetOpenFileNameViaDlg(openInfo); if (hr == VSConstants.OLE_E_PROMPTSAVECANCELLED) { return(null); } ErrorHandler.ThrowOnFailure(hr); return(Marshal.PtrToStringAuto(openInfo[0].pwzFileName)); } finally { if (pFileName != IntPtr.Zero) { Marshal.FreeCoTaskMem(pFileName); } } }
private static void SetIconInfo(List <Icon> aIcons) { if (aIcons == null) { throw new ArgumentNullException("aIcons"); } if (aIcons.Count == 0) { return; } //取桌面ListView句柄 IntPtr hDeskTop = WinAPI.FindWindow("progman", null); hDeskTop = WinAPI.FindWindowEx(hDeskTop, IntPtr.Zero, "shelldll_defview", null); hDeskTop = WinAPI.FindWindowEx(hDeskTop, IntPtr.Zero, "syslistview32", null); //取explorer.exe句柄 int dwProcessId; WinAPI.GetWindowThreadProcessId(hDeskTop, out dwProcessId); IntPtr hProcess = WinAPI.OpenProcess(WinAPI.PROCESS_VM_OPERATION | WinAPI.PROCESS_VM_READ | WinAPI.PROCESS_VM_WRITE, false, dwProcessId); unsafe { //在 explorer.exe 空间内分配内存 IntPtr pv = WinAPI.VirtualAllocEx(hProcess, IntPtr.Zero, sizeof(Point), WinAPI.MEM_COMMIT, WinAPI.PAGE_READWRITE); IntPtr pn = WinAPI.VirtualAllocEx(hProcess, IntPtr.Zero, WinAPI.MAX_PATH * 2, WinAPI.MEM_COMMIT, WinAPI.PAGE_READWRITE); IntPtr plvitem = WinAPI.VirtualAllocEx(hProcess, IntPtr.Zero, WinAPI.GetLvItemSize(), WinAPI.MEM_COMMIT, WinAPI.PAGE_READWRITE); //发送获取坐标消息 int count = WinAPI.ListView_GetItemCount(hDeskTop); for (int i = 0; i < count; i++) { WinAPI.ListView_GetItemText(hDeskTop, i, hProcess, plvitem, (int)pn, WinAPI.MAX_PATH * 2); //读取文本数据 IntPtr pszName = Marshal.AllocCoTaskMem(WinAPI.MAX_PATH * 2); int lpNumberOfBytesRead; WinAPI.ReadProcessMemory(hProcess, pn, pszName, WinAPI.MAX_PATH * 2, out lpNumberOfBytesRead); string text = Marshal.PtrToStringUni(pszName); Marshal.FreeCoTaskMem(pszName); //判断包含列表 Icon icon = aIcons.SingleOrDefault(item => item.Text == text); if (icon == null) { continue; } //设置坐标 WinAPI.ListView_SetItemPosition(hDeskTop, i, icon.Position.x, icon.Position.y); } //释放内存 WinAPI.VirtualFreeEx(hProcess, pv, sizeof(Point), 0); WinAPI.VirtualFreeEx(hProcess, pn, WinAPI.MAX_PATH * 2, 0); WinAPI.VirtualFreeEx(hProcess, plvitem, WinAPI.GetLvItemSize(), 0); //释放句柄 WinAPI.CloseHandle(hProcess); } }
public static (bool success, List <AmdBusIDInfo> busIdInfos) TryQuery(Dictionary <int, string> amdBusIdAndUuids) { var busIdInfos = new List <AmdBusIDInfo>(); var success = false; var adapterBuffer = IntPtr.Zero; try { var numberOfAdapters = 0; var adlRet = ADL.ADL_Main_Control_Create?.Invoke(ADL.ADL_Main_Memory_Alloc, 1); AdlThrowIfException(adlRet, nameof(ADL.ADL_Main_Control_Create)); adlRet = ADL.ADL_Adapter_NumberOfAdapters_Get?.Invoke(ref numberOfAdapters); AdlThrowIfException(adlRet, nameof(ADL.ADL_Adapter_NumberOfAdapters_Get)); Logger.Info(Tag, $"Number Of Adapters: {numberOfAdapters}"); if (numberOfAdapters <= 0) { throw new Exception("Did not find any ADL adapters"); } // Get OS adpater info from ADL var osAdapterInfoData = new ADLAdapterInfoArray(); var size = Marshal.SizeOf(osAdapterInfoData); adapterBuffer = Marshal.AllocCoTaskMem(size); Marshal.StructureToPtr(osAdapterInfoData, adapterBuffer, false); adlRet = ADL.ADL_Adapter_AdapterInfo_Get?.Invoke(adapterBuffer, size); AdlThrowIfException(adlRet, nameof(ADL.ADL_Adapter_AdapterInfo_Get)); osAdapterInfoData = (ADLAdapterInfoArray)Marshal.PtrToStructure(adapterBuffer, osAdapterInfoData.GetType()); var adl2Info = TryGetAdl2AdapterInfo(); var isActive = 0; for (var i = 0; i < numberOfAdapters; i++) { var adapter = osAdapterInfoData.ADLAdapterInfo[i]; // Check if the adapter is active adlRet = ADL.ADL_Adapter_Active_Get?.Invoke(adapter.AdapterIndex, ref isActive); if (ADL.ADL_SUCCESS != adlRet) { continue; } if (!IsAmdAdapter(adapter)) { continue; } if (!amdBusIdAndUuids.ContainsKey(adapter.BusNumber)) { continue; } var adl2Index = -1; if (adl2Info != null) { adl2Index = adl2Info .FirstOrDefault(a => a.UDID == adapter.UDID) .AdapterIndex; } var info = new AmdBusIDInfo { BusID = adapter.BusNumber, Uuid = amdBusIdAndUuids[adapter.BusNumber], Adl1Index = adapter.AdapterIndex, Adl2Index = adl2Index }; busIdInfos.Add(info); } success = true; } catch (Exception e) { Logger.Error(Tag, e.Message); Logger.Info(Tag, "Check if ADL is properly installed!"); success = false; } finally { try { if (adapterBuffer != IntPtr.Zero) { Marshal.FreeCoTaskMem(adapterBuffer); } } catch { } } return(success, busIdInfos); }
/// <summary> /// Gets the children. /// </summary> /// <param name="childTypes">The child types.</param> /// <returns> /// The children. /// </returns> public IEnumerable <ShellItem> GetChildren(ChildTypes childTypes) { // We'll return a list of children. var children = new List <ShellItem>(); // Create the enum flags from the childtypes. SHCONTF enumFlags = 0; if (childTypes.HasFlag(ChildTypes.Folders)) { enumFlags |= SHCONTF.SHCONTF_FOLDERS; } if (childTypes.HasFlag(ChildTypes.Files)) { enumFlags |= SHCONTF.SHCONTF_NONFOLDERS; } if (childTypes.HasFlag(ChildTypes.Hidden)) { enumFlags |= SHCONTF.SHCONTF_INCLUDEHIDDEN; } try { // Create an enumerator for the children. IEnumIDList pEnum; var result = ShellFolderInterface.EnumObjects(IntPtr.Zero, enumFlags, out pEnum); // Validate the result. if (result != 0) { // Throw the failure as an exception. Marshal.ThrowExceptionForHR((int)result); } // TODO: This logic should go in the pidl manager. // Enumerate the children, ten at a time. const int batchSize = 10; var pidlArray = Marshal.AllocCoTaskMem(IntPtr.Size * 10); uint itemsFetched; result = WinError.S_OK; do { result = pEnum.Next(batchSize, pidlArray, out itemsFetched); // Get each pidl. var pidls = new IntPtr[itemsFetched]; Marshal.Copy(pidlArray, pidls, 0, (int)itemsFetched); foreach (var childPidl in pidls) { // Create a new shell folder. var childShellFolder = new ShellItem(); // Initialize it. try { childShellFolder.Initialise(childPidl, this); } catch (Exception exception) { throw new InvalidOperationException("Failed to initialise child.", exception); } // Add the child. children.Add(childShellFolder); // Free the PIDL, reset the result. Marshal.FreeCoTaskMem(childPidl); } } while (result == WinError.S_OK); Marshal.FreeCoTaskMem(pidlArray); // Release the enumerator. if (Marshal.IsComObject(pEnum)) { Marshal.ReleaseComObject(pEnum); } } catch (Exception exception) { throw new InvalidOperationException("Failed to enumerate children.", exception); } // Sort the children. var sortedChildren = children.Where(c => c.IsFolder).ToList(); sortedChildren.AddRange(children.Where(c => !c.IsFolder)); // Return the children. return(sortedChildren); }
public static SslCertificateBinding[] GetSslCertificateBindings() { InitializeHttp(); try { var bindings = new List <SslCertificateBinding>(); uint recordNum = 0; while (true) { var inputConfigInfoQuery = new HTTP_SERVICE_CONFIG_SSL_QUERY { QueryDesc = HTTP_SERVICE_CONFIG_QUERY_TYPE.HttpServiceConfigQueryNext, dwToken = recordNum++ }; var size = Marshal.SizeOf(typeof(HTTP_SERVICE_CONFIG_SSL_QUERY)); var pInputConfigInfo = Marshal.AllocCoTaskMem(size); Marshal.StructureToPtr(inputConfigInfoQuery, pInputConfigInfo, false); var pOutputConfigInfo = Marshal.AllocCoTaskMem(0); var returnLength = 0; var retVal = HttpQueryServiceConfiguration(IntPtr.Zero, HTTP_SERVICE_CONFIG_ID.HttpServiceConfigSSLCertInfo, pInputConfigInfo, Marshal.SizeOf(inputConfigInfoQuery), pOutputConfigInfo, returnLength, out returnLength, IntPtr.Zero); if (Win32ErrorCodes.InsufficientBuffer == retVal) { Marshal.FreeCoTaskMem(pOutputConfigInfo); pOutputConfigInfo = Marshal.AllocCoTaskMem(Convert.ToInt32(returnLength)); retVal = HttpQueryServiceConfiguration(IntPtr.Zero, HTTP_SERVICE_CONFIG_ID.HttpServiceConfigSSLCertInfo, pInputConfigInfo, Marshal.SizeOf(inputConfigInfoQuery), pOutputConfigInfo, returnLength, out returnLength, IntPtr.Zero); } else if (Win32ErrorCodes.NoMoreItems == retVal) { break; } if (Win32ErrorCodes.Ok == retVal) { var outputConfigInfo = (HTTP_SERVICE_CONFIG_SSL_SET) Marshal.PtrToStructure(pOutputConfigInfo, typeof(HTTP_SERVICE_CONFIG_SSL_SET)); var paramInfo = outputConfigInfo.ParamDesc; ushort port; var ipAddress = ConvertSockAddrPtrToIPAddress(outputConfigInfo.KeyDesc.pIpPort, out port); var portBytes = BitConverter.GetBytes(port); var reversedPortBytes = new [] { portBytes[1], portBytes[0] }; port = BitConverter.ToUInt16(reversedPortBytes, 0); var hash = new byte[outputConfigInfo.ParamDesc.SslHashLength]; Marshal.Copy(outputConfigInfo.ParamDesc.pSslHash, hash, 0, hash.Length); var hex = new StringBuilder(hash.Length * 2); foreach (var b in hash) { hex.AppendFormat("{0:x2}", b); } var certificateHash = hex.ToString(); var appID = paramInfo.AppId; var storeName = ConvertToStoreName(paramInfo.pSslCertStoreName); var verifyClientCertRevocation = ((paramInfo.DefaultCertCheckMode & 1) == 0); var verifyRevocationUsingCachedClientCertsOnly = (paramInfo.DefaultCertCheckMode & 2) == 2; var usageCheckEnabled = (paramInfo.DefaultCertCheckMode & 16) == 0; var revocationFreshnessTime = (uint)paramInfo.DefaultRevocationFreshnessTime; var urlRetrievalTimeout = (uint)paramInfo.DefaultRevocationUrlRetrievalTimeout; string ctlIdentifier = paramInfo.pDefaultSslCtlIdentifier ?? String.Empty; string ctlStoreName = paramInfo.pDefaultSslCtlStoreName ?? String.Empty; var dsMapperUsageEnabled = paramInfo.DefaultFlags.HasFlag(SslParamDefaultFlags.UseDsMapper); var negotiateClientCertificate = paramInfo.DefaultFlags.HasFlag(SslParamDefaultFlags.NegotiateClientCert); var binding = new SslCertificateBinding(ipAddress, port, certificateHash, appID, storeName, verifyClientCertRevocation, verifyRevocationUsingCachedClientCertsOnly, usageCheckEnabled, revocationFreshnessTime, urlRetrievalTimeout, ctlIdentifier, ctlStoreName, dsMapperUsageEnabled, negotiateClientCertificate); bindings.Add(binding); } else { throw new Win32Exception(); } } return(bindings.ToArray()); } finally { TerminateHttp(); } }
private IEnumerable <INetFwRule> EnumerateRulesMatchingPrefix(string prefix) { // powershell example // (New-Object -ComObject HNetCfg.FwPolicy2).rules | Where-Object { $_.Name -match '^prefix' } | ForEach-Object { Write-Output "$($_.Name)" } // TODO: Revisit COM interface in .NET core 3.0 var e = policy.Rules.GetEnumeratorVariant(); object[] results = new object[64]; int count; IntPtr bufferLengthPointer = Marshal.AllocCoTaskMem(Marshal.SizeOf(typeof(int))); try { do { e.Next(results.Length, results, bufferLengthPointer); count = Marshal.ReadInt32(bufferLengthPointer); foreach (object o in results) { if ((o is INetFwRule rule) && (prefix == "*" || rule.Name.StartsWith(prefix))) { yield return(rule); } } }while (count == results.Length); } finally { Marshal.FreeCoTaskMem(bufferLengthPointer); } /* * System.Diagnostics.Process p = new System.Diagnostics.Process * { * StartInfo = new System.Diagnostics.ProcessStartInfo * { * Arguments = "advfirewall firewall show rule name=all", * CreateNoWindow = true, * FileName = "netsh.exe", * UseShellExecute = false, * RedirectStandardOutput = true * } * }; * p.Start(); * string line; * string ruleName; * INetFwRule rule; * Regex regex = new Regex(": +" + prefix + ".*"); * Match match; * * while ((line = p.StandardOutput.ReadLine()) != null) * { * match = regex.Match(line); * if (match.Success) * { * ruleName = match.Value.Trim(' ', ':'); * rule = null; * try * { * rule = policy.Rules.Item(ruleName); * } * catch * { * } * if (rule != null) * { * yield return rule; * } * } * } */ }
private bool PromptForCredentialsCredUIWin(IntPtr owner, bool storedCredentials) { NativeMethods.CREDUI_INFO info = CreateCredUIInfo(owner, false); NativeMethods.CredUIWinFlags flags = NativeMethods.CredUIWinFlags.Generic; if (ShowSaveCheckBox) { flags |= NativeMethods.CredUIWinFlags.Checkbox; } IntPtr inBuffer = IntPtr.Zero; IntPtr outBuffer = IntPtr.Zero; try { uint inBufferSize = 0; if (UserName.Length > 0) { NativeMethods.CredPackAuthenticationBuffer(0, UserName, Password, IntPtr.Zero, ref inBufferSize); if (inBufferSize > 0) { inBuffer = Marshal.AllocCoTaskMem((int)inBufferSize); if (!NativeMethods.CredPackAuthenticationBuffer(0, UserName, Password, inBuffer, ref inBufferSize)) { throw new CredentialException(Marshal.GetLastWin32Error()); } } } uint outBufferSize; uint package = 0; NativeMethods.CredUIReturnCodes result = NativeMethods.CredUIPromptForWindowsCredentials(ref info, 0, ref package, inBuffer, inBufferSize, out outBuffer, out outBufferSize, ref _isSaveChecked, flags); switch (result) { case NativeMethods.CredUIReturnCodes.NO_ERROR: StringBuilder userName = new StringBuilder(NativeMethods.CREDUI_MAX_USERNAME_LENGTH); StringBuilder password = new StringBuilder(NativeMethods.CREDUI_MAX_PASSWORD_LENGTH); uint userNameSize = (uint)userName.Capacity; uint passwordSize = (uint)password.Capacity; uint domainSize = 0; if (!NativeMethods.CredUnPackAuthenticationBuffer(0, outBuffer, outBufferSize, userName, ref userNameSize, null, ref domainSize, password, ref passwordSize)) { throw new CredentialException(Marshal.GetLastWin32Error()); } UserName = userName.ToString(); Password = password.ToString(); if (ShowSaveCheckBox) { _confirmTarget = Target; // If the credential was stored previously but the user has now cleared the save checkbox, // we want to delete the credential. if (storedCredentials && !IsSaveChecked) { DeleteCredential(Target); } } return(true); case NativeMethods.CredUIReturnCodes.ERROR_CANCELLED: return(false); default: throw new CredentialException((int)result); } } finally { if (inBuffer != IntPtr.Zero) { Marshal.FreeCoTaskMem(inBuffer); } if (outBuffer != IntPtr.Zero) { Marshal.FreeCoTaskMem(outBuffer); } } }
bool disposed; // 생성된 객체가 Dispose가 불려서, 메모리 해제가 끝났는지 확인 public UnmanagedMemoryManager() // 생성자 { // Marshal은 관리되지 않는 컬렉션, 변환, 할당 등등에 대한 기능을 제공한다. pBuffer = Marshal.AllocCoTaskMem(4096 * 1024); // 의도적으로 4MB 할당 }
// http://d.hatena.ne.jp/espresso3389/20100413/1271152244 public static IntegrityLevel GetIntegrityLevel() { IntPtr pId = (Process.GetCurrentProcess().Handle); IntPtr hToken = IntPtr.Zero; if (OpenProcessToken(pId, TOKEN_QUERY, out hToken)) { try { IntPtr pb = Marshal.AllocCoTaskMem(1000); try { uint cb = 1000; if (GetTokenInformation(hToken, TOKEN_INFORMATION_CLASS.TokenIntegrityLevel, pb, cb, out cb)) { IntPtr pSid = Marshal.ReadIntPtr(pb); int dwIntegrityLevel = Marshal.ReadInt32(GetSidSubAuthority(pSid, (Marshal.ReadByte(GetSidSubAuthorityCount(pSid)) - 1U))); if (dwIntegrityLevel == SECURITY_MANDATORY_LOW_RID) { return(IntegrityLevel.Low); } else if (dwIntegrityLevel >= SECURITY_MANDATORY_MEDIUM_RID && dwIntegrityLevel < SECURITY_MANDATORY_HIGH_RID) { // Medium Integrity return(IntegrityLevel.Medium); } else if (dwIntegrityLevel >= SECURITY_MANDATORY_HIGH_RID) { // High Integrity return(IntegrityLevel.High); } else if (dwIntegrityLevel >= SECURITY_MANDATORY_SYSTEM_RID) { // System Integrity return(IntegrityLevel.System); } return(IntegrityLevel.None); } else { int errno = Marshal.GetLastWin32Error(); if (errno == ERROR_INVALID_PARAMETER) { throw new NotSupportedException(); } throw new Win32Exception(errno); } } finally { Marshal.FreeCoTaskMem(pb); } } finally { CloseHandle(hToken); } } { int errno = Marshal.GetLastWin32Error(); throw new Win32Exception(errno); } }
/// <summary> /// Set IE settings. /// </summary> private static void SetIEProxy(bool enable, bool global, string proxyServer, string pacURL, string connName) { List <INTERNET_PER_CONN_OPTION> _optionlist = new List <INTERNET_PER_CONN_OPTION>(); if (enable) { if (global) { // global proxy _optionlist.Add(new INTERNET_PER_CONN_OPTION { dwOption = (int)INTERNET_PER_CONN_OptionEnum.INTERNET_PER_CONN_FLAGS_UI, Value = { dwValue = (int)(INTERNET_OPTION_PER_CONN_FLAGS_UI.PROXY_TYPE_PROXY | INTERNET_OPTION_PER_CONN_FLAGS_UI.PROXY_TYPE_DIRECT) } }); _optionlist.Add(new INTERNET_PER_CONN_OPTION { dwOption = (int)INTERNET_PER_CONN_OptionEnum.INTERNET_PER_CONN_PROXY_SERVER, Value = { pszValue = Marshal.StringToHGlobalAuto(proxyServer) } }); _optionlist.Add(new INTERNET_PER_CONN_OPTION { dwOption = (int)INTERNET_PER_CONN_OptionEnum.INTERNET_PER_CONN_PROXY_BYPASS, Value = { pszValue = Marshal.StringToHGlobalAuto("<local>") } }); } else { // pac _optionlist.Add(new INTERNET_PER_CONN_OPTION { dwOption = (int)INTERNET_PER_CONN_OptionEnum.INTERNET_PER_CONN_FLAGS_UI, Value = { dwValue = (int)INTERNET_OPTION_PER_CONN_FLAGS_UI.PROXY_TYPE_AUTO_PROXY_URL } }); _optionlist.Add(new INTERNET_PER_CONN_OPTION { dwOption = (int)INTERNET_PER_CONN_OptionEnum.INTERNET_PER_CONN_AUTOCONFIG_URL, Value = { pszValue = Marshal.StringToHGlobalAuto(pacURL) } }); } } else { // direct _optionlist.Add(new INTERNET_PER_CONN_OPTION { dwOption = (int)INTERNET_PER_CONN_OptionEnum.INTERNET_PER_CONN_FLAGS_UI, Value = { dwValue = (int)(INTERNET_OPTION_PER_CONN_FLAGS_UI.PROXY_TYPE_AUTO_DETECT | INTERNET_OPTION_PER_CONN_FLAGS_UI.PROXY_TYPE_DIRECT) } }); } // Get total length of INTERNET_PER_CONN_OPTIONs var len = _optionlist.Sum(each => Marshal.SizeOf(each)); // Allocate a block of memory of the options. IntPtr buffer = Marshal.AllocCoTaskMem(len); IntPtr current = buffer; // Marshal data from a managed object to an unmanaged block of memory. foreach (INTERNET_PER_CONN_OPTION eachOption in _optionlist) { Marshal.StructureToPtr(eachOption, current, false); current = (IntPtr)((int)current + Marshal.SizeOf(eachOption)); } // Initialize a INTERNET_PER_CONN_OPTION_LIST instance. INTERNET_PER_CONN_OPTION_LIST optionList = new INTERNET_PER_CONN_OPTION_LIST(); // Point to the allocated memory. optionList.pOptions = buffer; // Return the unmanaged size of an object in bytes. optionList.Size = Marshal.SizeOf(optionList); optionList.Connection = connName.IsNullOrEmpty() ? IntPtr.Zero // NULL means LAN : Marshal.StringToHGlobalAuto(connName); // TODO: not working if contains Chinese optionList.OptionCount = _optionlist.Count; optionList.OptionError = 0; int optionListSize = Marshal.SizeOf(optionList); // Allocate memory for the INTERNET_PER_CONN_OPTION_LIST instance. IntPtr intptrStruct = Marshal.AllocCoTaskMem(optionListSize); // Marshal data from a managed object to an unmanaged block of memory. Marshal.StructureToPtr(optionList, intptrStruct, true); // Set internet settings. bool bReturn = NativeMethods.InternetSetOption( IntPtr.Zero, INTERNET_OPTION.INTERNET_OPTION_PER_CONNECTION_OPTION, intptrStruct, optionListSize); // Free the allocated memory. Marshal.FreeCoTaskMem(buffer); Marshal.FreeCoTaskMem(intptrStruct); // Throw an exception if this operation failed. if (!bReturn) { throw new ProxyException("InternetSetOption failed.", new Win32Exception()); } // Notify the system that the registry settings have been changed and cause // the proxy data to be reread from the registry for a handle. bReturn = NativeMethods.InternetSetOption( IntPtr.Zero, INTERNET_OPTION.INTERNET_OPTION_PROXY_SETTINGS_CHANGED, IntPtr.Zero, 0); if (!bReturn) { Logging.Error("InternetSetOption:INTERNET_OPTION_PROXY_SETTINGS_CHANGED"); } bReturn = NativeMethods.InternetSetOption( IntPtr.Zero, INTERNET_OPTION.INTERNET_OPTION_REFRESH, IntPtr.Zero, 0); if (!bReturn) { Logging.Error("InternetSetOption:INTERNET_OPTION_REFRESH"); } }
// --------------------------------------------------------------------------------------------- // OLE // --------------------------------------------------------------------------------------------- public IRichEditOle GetRichEditOleInterface() { if (IRichEditOleValue == null) { // Allocate the ptr that EM_GETOLEINTERFACE will fill in var ptr = Marshal.AllocCoTaskMem(Marshal.SizeOf(typeof(IntPtr))); // Alloc the ptr. Marshal.WriteIntPtr(ptr, IntPtr.Zero); // Clear it. try { if (0 != API.SendMessage(mRichBox.Handle, Messages.EM_GETOLEINTERFACE, IntPtr.Zero, ptr)) { // Read the returned pointer var pRichEdit = Marshal.ReadIntPtr(ptr); try { if (pRichEdit != IntPtr.Zero) { // Query for the IRichEditOle interface var guid = new Guid("00020D00-0000-0000-c000-000000000046"); Marshal.QueryInterface(pRichEdit, ref guid, out IRichEditOlePtr); // Wrap it in the C# interface for IRichEditOle IRichEditOleValue = (IRichEditOle)Marshal.GetTypedObjectForIUnknown(IRichEditOlePtr, typeof(IRichEditOle)); if (IRichEditOleValue == null) { throw new Exception( "Failed to get the object wrapper for the IRichEditOle interface."); } // IID_ITextDocument guid = new Guid("8CC497C0-A1DF-11CE-8098-00AA0047BE5D"); Marshal.QueryInterface(pRichEdit, ref guid, out ITextDocumentPtr); // Wrap it in the C# interface for IRichEditOle ITextDocumentValue = (ITextDocument)Marshal.GetTypedObjectForIUnknown(ITextDocumentPtr, typeof(ITextDocument)); if (ITextDocumentValue == null) { throw new Exception( "Failed to get the object wrapper for the ITextDocument interface."); } } else { throw new Exception("Failed to get the pointer."); } } finally { Marshal.Release(pRichEdit); } } else { throw new Exception("EM_GETOLEINTERFACE failed."); } } catch (Exception err) { Trace.WriteLine(err.ToString()); ReleaseRichEditOleInterface(); } finally { // Free the ptr memory Marshal.FreeCoTaskMem(ptr); } } return(IRichEditOleValue); }
public async Task SocketCanRead() { var loop = new UvLoopHandle(_logger); loop.Init(_uv); var tcp = new UvTcpHandle(_logger); tcp.Init(loop); var address = ServerAddress.FromUrl("http://localhost:54321/"); tcp.Bind(address); tcp.Listen(10, (_, status, error, state) => { Console.WriteLine("Connected"); var tcp2 = new UvTcpHandle(_logger); tcp2.Init(loop); tcp.Accept(tcp2); var data = Marshal.AllocCoTaskMem(500); tcp2.ReadStart( (a, b, c) => _uv.buf_init(data, 500), (__, nread, state2) => { if (nread <= 0) { tcp2.Dispose(); } }, null); tcp.Dispose(); }, null); Console.WriteLine("Task.Run"); var t = Task.Run(async() => { var socket = new Socket( AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); #if DNX451 await Task.Factory.FromAsync( socket.BeginConnect, socket.EndConnect, new IPEndPoint(IPAddress.Loopback, 54321), null, TaskCreationOptions.None); await Task.Factory.FromAsync( socket.BeginSend, socket.EndSend, new[] { new ArraySegment <byte>(new byte[] { 1, 2, 3, 4, 5 }) }, SocketFlags.None, null, TaskCreationOptions.None); #else await socket.ConnectAsync(new IPEndPoint(IPAddress.Loopback, 54321)); await socket.SendAsync(new[] { new ArraySegment <byte>(new byte[] { 1, 2, 3, 4, 5 }) }, SocketFlags.None); #endif socket.Dispose(); }); loop.Run(); loop.Dispose(); await t; }
public NativeStreamWrapper(IStream source) { this.source = source; nativeLong = Marshal.AllocCoTaskMem(8); }
public async Task SocketCanReadAndWrite() { var loop = new UvLoopHandle(_logger); loop.Init(_uv); var tcp = new UvTcpHandle(_logger); tcp.Init(loop); var address = ServerAddress.FromUrl("http://localhost:54321/"); tcp.Bind(address); tcp.Listen(10, (_, status, error, state) => { Console.WriteLine("Connected"); var tcp2 = new UvTcpHandle(_logger); tcp2.Init(loop); tcp.Accept(tcp2); var data = Marshal.AllocCoTaskMem(500); tcp2.ReadStart( (a, b, c) => tcp2.Libuv.buf_init(data, 500), (__, nread, state2) => { if (nread <= 0) { tcp2.Dispose(); } else { for (var x = 0; x < 2; x++) { var req = new UvWriteReq(new KestrelTrace(new TestKestrelTrace())); req.Init(loop); var block = MemoryPoolBlock2.Create( new ArraySegment <byte>(new byte[] { 65, 66, 67, 68, 69 }), dataPtr: IntPtr.Zero, pool: null, slab: null); var start = new MemoryPoolIterator2(block, 0); var end = new MemoryPoolIterator2(block, block.Data.Count); req.Write( tcp2, start, end, 1, (_1, _2, _3, _4) => { block.Unpin(); }, null); } } }, null); tcp.Dispose(); }, null); Console.WriteLine("Task.Run"); var t = Task.Run(async() => { var socket = new Socket( AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); #if DNX451 await Task.Factory.FromAsync( socket.BeginConnect, socket.EndConnect, new IPEndPoint(IPAddress.Loopback, 54321), null, TaskCreationOptions.None); await Task.Factory.FromAsync( socket.BeginSend, socket.EndSend, new[] { new ArraySegment <byte>(new byte[] { 1, 2, 3, 4, 5 }) }, SocketFlags.None, null, TaskCreationOptions.None); #else await socket.ConnectAsync(new IPEndPoint(IPAddress.Loopback, 54321)); await socket.SendAsync(new[] { new ArraySegment <byte>(new byte[] { 1, 2, 3, 4, 5 }) }, SocketFlags.None); #endif socket.Shutdown(SocketShutdown.Send); var buffer = new ArraySegment <byte>(new byte[2048]); while (true) { #if DNX451 var count = await Task.Factory.FromAsync( socket.BeginReceive, socket.EndReceive, new[] { buffer }, SocketFlags.None, null, TaskCreationOptions.None); #else var count = await socket.ReceiveAsync(new[] { buffer }, SocketFlags.None); #endif Console.WriteLine("count {0} {1}", count, System.Text.Encoding.ASCII.GetString(buffer.Array, 0, count)); if (count <= 0) { break; } } socket.Dispose(); }); loop.Run(); loop.Dispose(); await t; }
public IntPtr MarshalManagedToNative(object obj) { if (null == obj) { return(IntPtr.Zero); } PropVariantMarshalType marshalType = PropVariantMarshalType.Automatic; if (obj is PropVariant) { propVariantReference = (PropVariant)obj; obj = propVariantReference.Value; marshalType = propVariantReference.MarshalType; } IntPtr pNativeData = AllocatePropVariant(); if (null == obj) { } else if (!(obj is Array)) { if (marshalType == PropVariantMarshalType.Ascii) { var upv = new UnmanagedPropVariant { vt = (ushort)VarEnum.VT_LPSTR, pointerValue = Marshal.StringToCoTaskMemAnsi((string)obj) }; Marshal.StructureToPtr(upv, pNativeData, false); } else if (obj is DateTime) { var upv = new UnmanagedPropVariant { vt = (ushort)VarEnum.VT_FILETIME, int64Value = ((DateTime)obj).ToFileTimeUtc() }; Marshal.StructureToPtr(upv, pNativeData, false); } else if (obj is string) { var upv = new UnmanagedPropVariant { vt = (ushort)VarEnum.VT_LPWSTR, pointerValue = Marshal.StringToCoTaskMemUni((string)obj) }; Marshal.StructureToPtr(upv, pNativeData, false); } else { Marshal.GetNativeVariantForObject(obj, pNativeData); } } else if ((obj.GetType().Equals(typeof(byte[]))) || (obj.GetType().Equals(typeof(sbyte[]))) || (obj.GetType().Equals(typeof(Int16[]))) || (obj.GetType().Equals(typeof(UInt16[]))) || (obj.GetType().Equals(typeof(Int32[]))) || (obj.GetType().Equals(typeof(UInt32[]))) || (obj.GetType().Equals(typeof(Int64[]))) || (obj.GetType().Equals(typeof(UInt64[]))) || (obj.GetType().Equals(typeof(float[]))) || (obj.GetType().Equals(typeof(double[])))) { int count = ((Array)obj).Length; int elementSize = Marshal.SizeOf(obj.GetType().GetElementType()); IntPtr pNativeBuffer = Marshal.AllocCoTaskMem(elementSize * count); for (int i = 0; i < count; i++) { IntPtr pNativeValue = Marshal.UnsafeAddrOfPinnedArrayElement((Array)obj, i); for (int j = 0; j < elementSize; j++) { byte value = Marshal.ReadByte(pNativeValue, j); Marshal.WriteByte(pNativeBuffer, j + i * elementSize, value); } } UnmanagedPropVariant upv = new UnmanagedPropVariant(); upv.vectorValue.count = (uint)count; upv.vectorValue.ptr = pNativeBuffer; if (null == propVariantReference) { upv.vt = (ushort)(new PropVariant(obj)).GetUnmanagedType(); } else { upv.vt = (ushort)propVariantReference.GetUnmanagedType(); } Marshal.StructureToPtr(upv, pNativeData, false); } else if (obj.GetType().Equals(typeof(string[]))) { int count = ((Array)obj).Length; IntPtr pNativeBuffer = Marshal.AllocCoTaskMem(IntPtr.Size * count); for (int i = 0; i < count; i++) { IntPtr strPtr = Marshal.StringToCoTaskMemUni(((string[])obj)[i]); Marshal.WriteIntPtr(pNativeBuffer, IntPtr.Size * i, strPtr); } UnmanagedPropVariant upv = new UnmanagedPropVariant(); upv.vectorValue.count = (uint)count; upv.vectorValue.ptr = pNativeBuffer; if (null == propVariantReference) { upv.vt = (ushort)(new PropVariant(obj)).GetUnmanagedType(); } else { upv.vt = (ushort)propVariantReference.GetUnmanagedType(); } Marshal.StructureToPtr(upv, pNativeData, false); } else { throw new NotImplementedException(); } return(pNativeData); }
protected static void GetFileInformation(String name, ref long length, ref IntPtr pDataUnManaged) { #if UNITY_ANDROID long start; Int32 fd; IntPtr cls_Activity = (IntPtr)AndroidJNI.FindClass("com/unity3d/player/UnityPlayer"); IntPtr fid_Activity = AndroidJNI.GetStaticFieldID(cls_Activity, "currentActivity", "Landroid/app/Activity;"); IntPtr obj_Activity = AndroidJNI.GetStaticObjectField(cls_Activity, fid_Activity); IntPtr obj_cls = AndroidJNI.GetObjectClass(obj_Activity); IntPtr asset_func = AndroidJNI.GetMethodID(obj_cls, "getAssets", "()Landroid/content/res/AssetManager;"); IntPtr assetManager = AndroidJNI.CallObjectMethod(obj_Activity, asset_func, new jvalue[2]); IntPtr assetManagerClass = AndroidJNI.GetObjectClass(assetManager); IntPtr openFd = AndroidJNI.GetMethodID(assetManagerClass, "openFd", "(Ljava/lang/String;)Landroid/content/res/AssetFileDescriptor;"); jvalue[] param_array2 = new jvalue[2]; jvalue param = new jvalue(); param.l = AndroidJNI.NewStringUTF(name); param_array2[0] = param; IntPtr jfd; try { jfd = AndroidJNI.CallObjectMethod(assetManager, openFd, param_array2); IntPtr assetFdClass = AndroidJNI.GetObjectClass(jfd); IntPtr getParcelFd = AndroidJNI.GetMethodID(assetFdClass, "getParcelFileDescriptor", "()Landroid/os/ParcelFileDescriptor;"); IntPtr getStartOffset = AndroidJNI.GetMethodID(assetFdClass, "getStartOffset", "()J"); IntPtr getLength = AndroidJNI.GetMethodID(assetFdClass, "getLength", "()J"); start = AndroidJNI.CallLongMethod(jfd, getStartOffset, new jvalue[2]); length = AndroidJNI.CallLongMethod(jfd, getLength, new jvalue[2]); IntPtr fileInputStreamId = AndroidJNI.GetMethodID(assetFdClass, "createInputStream", "()Ljava/io/FileInputStream;"); IntPtr fileInputStream = AndroidJNI.CallObjectMethod(jfd, fileInputStreamId, new jvalue[2]); IntPtr fileInputStreamClass = AndroidJNI.GetObjectClass(fileInputStream); // Method signatures:newbytear B: byte, Z: boolean IntPtr read = AndroidJNI.GetMethodID(fileInputStreamClass, "read", "([BII)I"); jvalue[] param_array = new jvalue[3]; jvalue param1 = new jvalue(); IntPtr pData = AndroidJNI.NewByteArray((int)(length)); param1.l = pData; jvalue param2 = new jvalue(); param2.i = 0; jvalue param3 = new jvalue(); param3.i = (int)(length); param_array[0] = param1; param_array[1] = param2; param_array[2] = param3; int numBytesRead = AndroidJNI.CallIntMethod(fileInputStream, read, param_array); UnityEngine.Debug.Log("Bytes Read = " + numBytesRead); Byte[] pDataManaged = AndroidJNI.FromByteArray(pData); pDataUnManaged = Marshal.AllocCoTaskMem((int)length); Marshal.Copy(pDataManaged, 0, pDataUnManaged, (int)length); jfd = AndroidJNI.CallObjectMethod(jfd, getParcelFd, new jvalue[2]); IntPtr parcelFdClass = AndroidJNI.GetObjectClass(jfd); jvalue[] param_array3 = new jvalue[2]; IntPtr getFd = AndroidJNI.GetMethodID(parcelFdClass, "getFileDescriptor", "()Ljava/io/FileDescriptor;"); jfd = AndroidJNI.CallObjectMethod(jfd, getFd, param_array3); IntPtr fdClass = AndroidJNI.GetObjectClass(jfd); IntPtr descriptor = AndroidJNI.GetFieldID(fdClass, "descriptor", "I"); fd = AndroidJNI.GetIntField(jfd, descriptor); } catch (IOException ex) { UnityEngine.Debug.Log("IO Exception: Failed to load swf file"); } #endif return; }