System.IntPtr.ToInt64()

Here are the examples of the csharp api System.IntPtr.ToInt64() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

967 Examples 7

19 View Source File : NativeMethods.cs
License : MIT License
Project Creator : AlexeiScherbakov

[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
		internal static bool IsValidHandle(IntPtr handle)
		{
			// if (?:) will be eliminated by jit
			return (IntPtr.Size == 4)
				? (handle.ToInt32() > 0)
				: (handle.ToInt64() > 0);
		}

19 View Source File : nfapinet.cs
License : MIT License
Project Creator : AmazingDM

public static NF_STATUS nf_setRules(NF_RULE[] rules)
        {
            NF_RULE pRule;

            IntPtr ptr = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(NF_RULE)) * rules.Length);

            long longPtr = ptr.ToInt64();
            for (int i = 0; i < rules.Length; i++)
            {
                pRule = rules[i];

                updateAddressLength(ref pRule.localIpAddress);
                updateAddressLength(ref pRule.localIpAddressMask);
                updateAddressLength(ref pRule.remoteIpAddress);
                updateAddressLength(ref pRule.remoteIpAddressMask);

                Marshal.StructureToPtr(pRule, new IntPtr(longPtr), false);

                longPtr += Marshal.SizeOf(typeof(NF_RULE));
            }

            return nf_setRules(ptr, rules.Length);
        }

19 View Source File : SharedMemory.cs
License : GNU General Public License v3.0
Project Creator : aiportal

public byte[] GetData(int millisecondsTimeout = Timeout.Infinite)
		{
			byte[] buffer = null;
			this.MutexInvoke(() =>
			{
				int size = Marshal.ReadInt32(this._memory, 4);
				buffer = new byte[size];

				IntPtr pData = new IntPtr(this._memory.ToInt64() + 8);
				Marshal.Copy(pData, buffer, 0, buffer.Length);

			}, millisecondsTimeout);
			return buffer;
		}

19 View Source File : TcpEngine.cs
License : GNU General Public License v3.0
Project Creator : aiportal

private static IEnumerable<MIB_TCP6ROW_OWNER_PID> EnumTcpConnectionsV6()
		{
			int dwSize = sizeof(int) + Marshal.SizeOf(typeof(MIB_TCP6ROW_OWNER_PID)) * 100;
			IntPtr hTcpTable = IntPtr.Zero;
			{
				hTcpTable = Marshal.AllocHGlobal(dwSize);
				int ret = iphlpapi.GetExtendedTcpTable(hTcpTable, ref dwSize, true, util.AF_INET6, TCP_TABLE_CLreplaced.TCP_TABLE_OWNER_PID_CONNECTIONS, 0);
				if (ret != util.NO_ERROR)
				{
					// retry for new dwSize.
					Marshal.FreeHGlobal(hTcpTable);
					hTcpTable = Marshal.AllocHGlobal(dwSize);
					ret = iphlpapi.GetExtendedTcpTable(hTcpTable, ref dwSize, true, util.AF_INET6, TCP_TABLE_CLreplaced.TCP_TABLE_OWNER_PID_CONNECTIONS, 0);
					if (ret != util.NO_ERROR)
					{
						Marshal.FreeHGlobal(hTcpTable);
						throw new Exception("GetExtendedTcpTable return: " + ret);
					}
				}
			}
			{
				MIB_TCP6ROW_OWNER_PID item = new MIB_TCP6ROW_OWNER_PID();
				int dwNumEntries = Marshal.ReadInt32(hTcpTable);
				IntPtr pItem = new IntPtr(hTcpTable.ToInt32() + sizeof(int));
				for (int i = 0; i < dwNumEntries; ++i)
				{
					//var item = (MIB_TCP6ROW_OWNER_PID)Marshal.PtrToStructure(pItem, typeof(MIB_TCP6ROW_OWNER_PID));
					Marshal.PtrToStructure(pItem, item);
					pItem = new IntPtr(pItem.ToInt64() + Marshal.SizeOf(typeof(MIB_TCP6ROW_OWNER_PID)));
					yield return item;
				}
				Marshal.FreeHGlobal(hTcpTable);
			}
		}

19 View Source File : ImageCompressEngine.cs
License : GNU General Public License v3.0
Project Creator : aiportal

public static Image CreateImageByData(byte[] bsData, int width, int height, ColorPalette palette)
		{
			Image img;
			try
			{
				Rectangle rect = new Rectangle(0, 0, width, height);
				PixelFormat format = palette == null ? PixelFormat.Format16bppRgb555 : PixelFormat.Format8bppIndexed;

				Bitmap bmp = new Bitmap(width, height, format);
				if (palette != null)
					bmp.Palette = palette;

				var bmpData = bmp.LockBits(rect, ImageLockMode.WriteOnly, format);
				{
					int length = Math.Abs(bmpData.Stride) * bmpData.Height;
					IntPtr pData = new IntPtr(bmpData.Scan0.ToInt64() + (bmpData.Stride > 0 ? 0 : bmpData.Stride * (bmpData.Height - 1)));

					Debug.replacedert(bsData.Length >= length);
					Marshal.Copy(bsData, 0, pData, length);
				}
				bmp.UnlockBits(bmpData);
				img = bmp;
			}
			catch (Exception ex) { TraceLogger.Instance.WriteException(ex); throw; }
			return img;
		}

19 View Source File : Win32Ptr.cs
License : Apache License 2.0
Project Creator : aequabit

public static IntPtr Subtract(this IntPtr ptr, long val)
        {
            return new IntPtr((int) (ptr.ToInt64() - val));
        }

19 View Source File : Program.cs
License : MIT License
Project Creator : Alexx999

private static void Dump(SafeProcessHandle process, string outFileName, IntPtr address, IntPtr length, bool unprotect)
        {
            using (var file = File.Create(outFileName))
            {
                IntPtr read;
                using (var mmf = MemoryMappedFile.CreateFromFile(file, null, length.ToInt64(), MemoryMappedFileAccess.ReadWrite, null, HandleInheritability.None, true))
                using (var accessor = mmf.CreateViewAccessor(0, 0, MemoryMappedFileAccess.Write))
                {
                    var buffer = (SafeBuffer) accessor.SafeMemoryMappedViewHandle;
                    var ptr = buffer.DangerousGetHandle();
                    if (!ReadProcessMemory(process.DangerousGetHandle(), address, ptr, length, out read))
                    {
                        var error = Marshal.GetLastWin32Error();
                        Console.WriteLine($"Reading process memory failed with error 0x{error:8X}");
                        if (error == 299 && !unprotect)
                        {
                            Console.WriteLine("You can try -unprotect option");
                        }
                    }
                }

                if (read != length)
                {
                    Console.WriteLine($"Data was read partially - {read.ToInt64()} bytes out of {length.ToInt64()} bytes requested");
                    file.SetLength(read.ToInt64());
                }
            }
        }

19 View Source File : Ryder.Lightweight.cs
License : MIT License
Project Creator : 71

internal static void AllowRW(IntPtr address)
            {
                if (IsARM)
                    return;

                if (IsWindows)
                {
                    if (VirtualProtect(address, new UIntPtr(1), 0x40 /* PAGE_EXECUTE_READWRITE */, out var _))
                        return;

                    goto Error;
                }

                long pagesize = IsLinux ? LinuxGetPageSize() : OsxGetPageSize();
                long start = address.ToInt64();
                long pagestart = start & -pagesize;

                int buffsize = IntPtr.Size == sizeof(int) ? 6 : 12;

                if (IsLinux && LinuxProtect(new IntPtr(pagestart), (ulong)(start + buffsize - pagestart), 0x7 /* PROT_READ_WRITE_EXEC */) == 0)
                    return;
                if (!IsLinux && OsxProtect(new IntPtr(pagestart), (ulong)(start + buffsize - pagestart), 0x7 /* PROT_READ_WRITE_EXEC */) == 0)
                    return;

                Error:
                throw new Exception($"Unable to make method memory readable and writable. Error code: {Marshal.GetLastWin32Error()}");
            }

19 View Source File : OverlayForm.cs
License : GNU General Public License v2.0
Project Creator : AmanoTooko

private void OnKeyEvent(ref Message m)
    {
      CefKeyEvent keyEvent = new CefKeyEvent();
      keyEvent.WindowsKeyCode = m.WParam.ToInt32();
      keyEvent.NativeKeyCode = (int) m.LParam.ToInt64();
      keyEvent.IsSystemKey = m.Msg == 262 || m.Msg == 260 || m.Msg == 261;
      keyEvent.EventType = m.Msg == 256 || m.Msg == 260 ? CefKeyEventType.RawKeyDown : (m.Msg == 257 || m.Msg == 261 ? CefKeyEventType.KeyUp : CefKeyEventType.Char);
      keyEvent.Modifiers = this.GetKeyboardModifiers(ref m);
      if (this.Renderer == null)
        return;
      this.Renderer.SendKeyEvent(keyEvent);
    }

19 View Source File : OvrAvatarAssetMesh.cs
License : MIT License
Project Creator : absurd-joy

private void LoadBlendShapes(IntPtr replacedet, long vertexCount)
    {
        UInt32 blendShapeCount = CAPI.ovrAvatarreplacedet_GetMeshBlendShapeCount(replacedet);
        IntPtr blendShapeVerts = CAPI.ovrAvatarreplacedet_GetMeshBlendShapeVertices(replacedet);

        AvatarLogger.Log("LoadBlendShapes: " + blendShapeCount);

        if (blendShapeVerts != IntPtr.Zero)
        {
            long offset = 0;
            long blendVertexSize = (long)Marshal.SizeOf(typeof(ovrAvatarBlendVertex));
            long blendVertexBufferStart = blendShapeVerts.ToInt64();

            for (UInt32 blendIndex = 0; blendIndex < blendShapeCount; blendIndex++)
            {
                Vector3[] blendVerts = new Vector3[vertexCount];
                Vector3[] blendNormals = new Vector3[vertexCount];
                Vector3[] blendTangents = new Vector3[vertexCount];

                for (long i = 0; i < vertexCount; i++)
                {
                    ovrAvatarBlendVertex vertex = (ovrAvatarBlendVertex)Marshal.PtrToStructure(new IntPtr(blendVertexBufferStart + offset), typeof(ovrAvatarBlendVertex));
                    blendVerts[i] = new Vector3(vertex.x, vertex.y, -vertex.z);
                    blendNormals[i] = new Vector3(vertex.nx, vertex.ny, -vertex.nz);
                    blendTangents[i] = new Vector4(vertex.tx, vertex.ty, -vertex.tz);

                    offset += blendVertexSize;
                }

                IntPtr namePtr = CAPI.ovrAvatarreplacedet_GetMeshBlendShapeName(replacedet, blendIndex);
                string name = Marshal.PtrToStringAnsi(namePtr);
                const float frameWeight = 100f;
                mesh.AddBlendShapeFrame(name, frameWeight, blendVerts, blendNormals, blendTangents);
            }
        }
    }

19 View Source File : UserManager.cs
License : GNU General Public License v3.0
Project Creator : aiportal

public static IEnumerable<DomainUser> EnumLocalUsers(bool sid = false)
		{
			int read;
			int total;
			int resume;
			IntPtr buf;

			int ret = netapi.NetUserEnum(null, 10, util.FILTER_NORMAL_ACCOUNT, out buf, util.MAX_PREFERRED_LENGTH, out read, out total, out resume);
			if (ret != 0)
				throw new Win32Exception(ret);
			if (read > 0)
			{
				DomainUser user = new DomainUser();
				var u = new USER_INFO_10();
				IntPtr pItem = buf;
				for (int i = 0; i < read; ++i)
				{
					Marshal.PtrToStructure(pItem, u);
					pItem = new IntPtr(pItem.ToInt64() + Marshal.SizeOf(typeof(USER_INFO_10)));

					if (sid)
						user.SID = GetAccountSID(u.name);
					user.Name = u.name;
					user.FullName = u.full_name;
					user.Comment = u.comment;
					yield return user;
				}
				netapi.NetApiBufferFree(buf);
			}
		}

19 View Source File : ImageCompressEngine.cs
License : GNU General Public License v3.0
Project Creator : aiportal

public static byte[] ExtractImageData(Bitmap bitmap)
		{
			byte[] bsData = null;
			{
				int width = bitmap.Width;
				int height = bitmap.Height;
				Rectangle rect = new Rectangle(0, 0, width, height);

				var data = bitmap.LockBits(rect, ImageLockMode.ReadOnly, bitmap.PixelFormat);
				try
				{
					IntPtr pData = new IntPtr(data.Scan0.ToInt64() + (data.Stride > 0 ? 0 : data.Stride * (height - 1)));
					int length = Math.Abs(data.Stride) * data.Height;
					bsData = new byte[length];
					Marshal.Copy(pData, bsData, 0, length);
				}
				catch (Exception ex) { TraceLogger.Instance.WriteException(ex); throw; }
				finally
				{
					bitmap.UnlockBits(data);
				}
			}
			return bsData;
		}

19 View Source File : Win32Ptr.cs
License : Apache License 2.0
Project Creator : aequabit

public static bool Compare(this IntPtr ptr, long value)
        {
            return (ptr.ToInt64() == value);
        }

19 View Source File : WindowUtils.cs
License : MIT License
Project Creator : AlexanderPro

public static WindowInformation GetWindowInformation(IntPtr hWnd)
        {
            var text = GetWindowText(hWnd);
            var wmText = GetWmGettext(hWnd);
            var clreplacedName = GetClreplacedName(hWnd);
            var realWindowClreplaced = RealGetWindowClreplaced(hWnd);
            var hWndParent = NativeMethods.GetParent(hWnd);
            var size = GetWindowSize(hWnd);
            var clientSize = GetWindowClientSize(hWnd);
            var isVisible = NativeMethods.IsWindowVisible(hWnd);
            var placement = GetWindowPlacement(hWnd);
            var threadId = NativeMethods.GetWindowThreadProcessId(hWnd, out var processId);
            var process = GetProcessByIdSafely(processId);

            var gwlStyle = NativeMethods.GetWindowLong(hWnd, NativeConstants.GWL_STYLE);
            var gwlExstyle = NativeMethods.GetWindowLong(hWnd, NativeConstants.GWL_EXSTYLE);
            var gwlUserData = NativeMethods.GetWindowLong(hWnd, NativeConstants.GWL_USERDATA);
            var gclStyle = NativeMethods.GetClreplacedLong(hWnd, NativeConstants.GCL_STYLE);
            var gclWndproc = NativeMethods.GetClreplacedLong(hWnd, NativeConstants.GCL_WNDPROC);
            var dwlDlgproc = NativeMethods.GetClreplacedLong(hWnd, NativeConstants.DWL_DLGPROC);
            var dwlUser = NativeMethods.GetClreplacedLong(hWnd, NativeConstants.DWL_USER);

            var windowDetailes = new Dictionary<string, string>();
            windowDetailes.Add("GetWindowText", text);
            windowDetailes.Add("WM_GETTEXT", wmText);
            windowDetailes.Add("GetClreplacedName", clreplacedName);
            windowDetailes.Add("RealGetClreplacedName", realWindowClreplaced);
            try
            {
                windowDetailes.Add("Font Name", GetFontName(hWnd));
            }
            catch
            {
            }

            windowDetailes.Add("Window Handle", $"0x{hWnd.ToInt64():X}");
            windowDetailes.Add("Parent Window Handle", hWndParent == IntPtr.Zero ? "-" : $"0x{hWndParent.ToInt64():X}");
            windowDetailes.Add("Is Window Visible", isVisible.ToString());
            windowDetailes.Add("Window Placement (showCmd)", placement.showCmd.ToString());
            windowDetailes.Add("Window Size", $"{size.Width}x{size.Height}");
            windowDetailes.Add("Window Client Size", $"{clientSize.Width}x{clientSize.Height}");

            try
            {
                var bounds = GetFrameBounds(hWnd);
                windowDetailes.Add("Window Extended Frame Bounds", $"{bounds.Top} {bounds.Right} {bounds.Bottom} {bounds.Left}");
            }
            catch
            {
            }

            try
            {
                windowDetailes.Add("Instance", $"0x{process.Modules[0].BaseAddress.ToInt64():X}");
            }
            catch
            {
            }
            
            windowDetailes.Add("GCL_WNDPROC", $"0x{gclWndproc:X}");
            windowDetailes.Add("DWL_DLGPROC", $"0x{dwlDlgproc:X}");
            windowDetailes.Add("GWL_STYLE", $"0x{gwlStyle:X}");
            windowDetailes.Add("GCL_STYLE", $"0x{gclStyle:X}");
            windowDetailes.Add("GWL_EXSTYLE", $"0x{gwlExstyle:X}");
            
            try
            {
                var windowInfo = new WINDOW_INFO();
                windowInfo.cbSize = Marshal.SizeOf(windowInfo);
                if (NativeMethods.GetWindowInfo(hWnd, ref windowInfo))
                {
                    windowDetailes.Add("WindowInfo.ExStyle", $"0x{windowInfo.dwExStyle:X}");
                }
            }
            catch
            {
            }
            
            try
            {
                uint key;
                Byte alpha;
                uint flags;
                var result = NativeMethods.GetLayeredWindowAttributes(hWnd, out key, out alpha, out flags);
                var layeredWindow = (LayeredWindow)flags;
                windowDetailes.Add("LWA_ALPHA", layeredWindow.HasFlag(LayeredWindow.LWA_ALPHA) ? "+" : "-");
                windowDetailes.Add("LWA_COLORKEY", layeredWindow.HasFlag(LayeredWindow.LWA_COLORKEY) ? "+" : "-");
            }
            catch
            {
            }
            
            windowDetailes.Add("GWL_USERDATA", $"0x{gwlUserData:X}");
            windowDetailes.Add("DWL_USER", $"0x{dwlUser:X}");

            var processDetailes = new Dictionary<string, string>();
            try
            {
                try
                {
                    processDetailes.Add("Full Path", process.MainModule.FileName);
                }
                catch
                {
                    var fileNameBuilder = new StringBuilder(1024);
                    var bufferLength = (uint)fileNameBuilder.Capacity + 1;
                    var fullPath = NativeMethods.QueryFullProcessImageName(process.Handle, 0, fileNameBuilder, ref bufferLength) ? fileNameBuilder.ToString() : "";
                    processDetailes.Add("Full Path", fullPath);
                }
            }
            catch
            {
            }

            var processInfo = (WmiProcessInfo)null;
            try
            {
                processInfo = GetWmiProcessInfo(processId);
                processDetailes.Add("Command Line", processInfo.CommandLine);
            }
            catch
            {
            }

            try
            {
                processDetailes.Add("Started at", $"{process.StartTime:dd.MM.yyyy HH:mm:ss}");
            }
            catch
            {
            }

            try
            {
                processDetailes.Add("Owner", processInfo.Owner);
            }
            catch
            {
            }

            processDetailes.Add("Process Id", processId.ToString());
            try
            {
                var parentProcess = process.GetParentProcess();
                processDetailes.Add("Parent Process Id", parentProcess.Id.ToString());
                processDetailes.Add("Parent", Path.GetFileName(parentProcess.MainModule.FileName));
            }
            catch
            {
            }
            
            processDetailes.Add("Thread Id", threadId.ToString());

            try
            {
                processDetailes.Add("Priority", process.GetProcessPriority().ToString());
            }
            catch
            {
            }

            
            try
            {
                processDetailes.Add("Threads", processInfo.ThreadCount.ToString());
                processDetailes.Add("Handles", processInfo.HandleCount.ToString());
                processDetailes.Add("Working Set Size", processInfo.WorkingSetSize.ToString());
                processDetailes.Add("Virtual Size", processInfo.VirtualSize.ToString());
            }
            catch
            {
            }
            
            try
            {
                var fileVersionInfo = process.MainModule.FileVersionInfo;
                processDetailes.Add("Product Name", fileVersionInfo.ProductName);
                processDetailes.Add("Copyright", fileVersionInfo.LegalCopyright);
                processDetailes.Add("File Version", fileVersionInfo.FileVersion);
                processDetailes.Add("Product Version", fileVersionInfo.ProductVersion);
            }
            catch
            {
            }

            return new WindowInformation(windowDetailes, processDetailes);
        }

19 View Source File : Helpers.cs
License : MIT License
Project Creator : 71

public static byte[] GetJmpBytes(IntPtr destination)
        {
            switch (RuntimeInformation.ProcessArchitecture)
            {
                case Architecture.Arm:
                {
                    // LDR PC, [PC, #-4]
                    // $addr
                    byte[] result = new byte[8];

                    result[0] = 0x04;
                    result[1] = 0xF0;
                    result[2] = 0x1F;
                    result[3] = 0xE5;

                    BitConverter.GetBytes(destination.ToInt32()).CopyTo(result, 4);

                    return result;
                }

                case Architecture.Arm64:
                {
                    // LDR PC, [PC, #-4]
                    // $addr
                    byte[] result = new byte[12];

                    result[0] = 0x04;
                    result[1] = 0xF0;
                    result[2] = 0x1F;
                    result[3] = 0xE5;

                    BitConverter.GetBytes(destination.ToInt64()).CopyTo(result, 4);

                    return result;
                }

                case Architecture.X64:
                {
                    // movabs rax,$addr
                    // jmp rax
                    byte[] result = new byte[12];

                    result[0] = 0x48;
                    result[1] = 0xB8;
                    result[10] = 0xFF;
                    result[11] = 0xE0;

                    BitConverter.GetBytes(destination.ToInt64()).CopyTo(result, 2);

                    return result;
                }

                case Architecture.X86:
                {
                    // push $addr
                    // ret
                    byte[] result = new byte[6];

                    result[0] = 0x68;
                    result[5] = 0xC3;

                    BitConverter.GetBytes(destination.ToInt32()).CopyTo(result, 1);

                    return result;
                }

                default:
                    throw UnsupportedArchitecture;
            }
        }

19 View Source File : MainForm.cs
License : MIT License
Project Creator : AlexGyver

protected override void WndProc(ref Message m) {
      const int WM_SYSCOMMAND = 0x112;
      const int SC_MINIMIZE = 0xF020;
      const int SC_CLOSE = 0xF060;

      if (minimizeToTray.Value &&
        m.Msg == WM_SYSCOMMAND && m.WParam.ToInt64() == SC_MINIMIZE) {
        SysTrayHideShow();
      } else if (minimizeOnClose.Value &&
        m.Msg == WM_SYSCOMMAND && m.WParam.ToInt64() == SC_CLOSE) {
        /*
         * Apparently the user wants to minimize rather than close
         * Now we still need to check if we're going to the tray or not
         * 
         * Note: the correct way to do this would be to send out SC_MINIMIZE,
         * but since the code here is so simple,
         * that would just be a waste of time.
         */
        if (minimizeToTray.Value) {
          SysTrayHideShow();
        } else {
          WindowState = FormWindowState.Minimized;
        }
      } else {
        base.WndProc(ref m);
      }
    }

19 View Source File : WTSEngine.cs
License : GNU General Public License v3.0
Project Creator : aiportal

public static bool IsSessionActive(int sessionId)
		{
			bool isActive = false;
			try
			{
				IntPtr pSessions = IntPtr.Zero;
				int count = 0;
				if (wtsapi32.WTSEnumerateSessions(IntPtr.Zero, 0, 1, ref pSessions, ref count))
				{
					WTS_SESSION_INFO si = new WTS_SESSION_INFO();
					IntPtr pSession = pSessions;
					for (int i = 0; i < count; ++i)
					{
						//WTS_SESSION_INFO si = (WTS_SESSION_INFO)Marshal.PtrToStructure(pSession, typeof(WTS_SESSION_INFO));
						Marshal.PtrToStructure(pSession, si);
						pSession = new IntPtr(pSession.ToInt64() + Marshal.SizeOf(typeof(WTS_SESSION_INFO)));
						if (si.SessionId == sessionId)
						{
							isActive = (si.State == WTS_CONNECTSTATE_CLreplaced.WTSActive);
							break;
						}
					}
					wtsapi32.WTSFreeMemory(pSessions);
				}
			}
			catch (Exception ex) { TraceLogger.Instance.WriteException(ex); throw; }
			return isActive;
		}

19 View Source File : OverlayBase`1.cs
License : GNU General Public License v2.0
Project Creator : AmanoTooko

private static int ToIntPtr32(IntPtr intPtr)
        {
            return (int)intPtr.ToInt64();
        }

19 View Source File : WebPNative.cs
License : MIT License
Project Creator : 0xC0000054

[System.Diagnostics.Codereplacedysis.SuppressMessage(
                "Microsoft.Design",
                "CA1031:DoNotCatchGeneralExceptionTypes",
                Justification = "The exception will be re-thrown after WebPSave returns the error code.")]
            public WebPEncodingError WriteImageCallback(IntPtr image, UIntPtr imageSize)
            {
                if (image == IntPtr.Zero)
                {
                    return WebPEncodingError.NullParameter;
                }

                if (imageSize == UIntPtr.Zero)
                {
                    // Ignore zero-length images.
                    return WebPEncodingError.Ok;
                }

                // 81920 is the largest multiple of 4096 that is below the large object heap threshold.
                const int MaxBufferSize = 81920;

                try
                {
                    long size = checked((long)imageSize.ToUInt64());

                    int bufferSize = (int)Math.Min(size, MaxBufferSize);

                    byte[] streamBuffer = new byte[bufferSize];

                    output.SetLength(size);

                    long offset = 0;
                    long remaining = size;

                    while (remaining > 0)
                    {
                        int copySize = (int)Math.Min(MaxBufferSize, remaining);

                        Marshal.Copy(new IntPtr(image.ToInt64() + offset), streamBuffer, 0, copySize);

                        output.Write(streamBuffer, 0, copySize);

                        offset += copySize;
                        remaining -= copySize;
                    }
                }
                catch (OperationCanceledException)
                {
                    return WebPEncodingError.UserAbort;
                }
                catch (Exception ex)
                {
                    WriteException = ex;
                    return WebPEncodingError.BadWrite;
                }

                return WebPEncodingError.Ok;
            }

19 View Source File : nfapinet.cs
License : MIT License
Project Creator : AmazingDM

public static void udpReceive(ulong id, IntPtr remoteAddress, IntPtr buf, int len, IntPtr options)
        {
            if (options.ToInt64() != 0)
            {
                NF_UDP_OPTIONS optionsCopy = (NF_UDP_OPTIONS)Marshal.PtrToStructure((IntPtr)options, typeof(NF_UDP_OPTIONS));
                int optionsLen = 8 + optionsCopy.optionsLength;
                m_pEventHandler.udpReceive(id, remoteAddress, buf, len, options, optionsLen);
            }
            else
            {
                m_pEventHandler.udpReceive(id, remoteAddress, buf, len, (IntPtr)null, 0);
            }
        }

19 View Source File : SystemUserAccess.cs
License : GNU General Public License v3.0
Project Creator : aiportal

public string[] GetUserGroups(string username)
		{
			List<string> groups = new List<string>();
			try
			{
				int entriesread;
				int totalentries;
				IntPtr pBuf;
				netapi32.NetUserGetLocalGroups(null, username, 0, 1,out pBuf, -1, out entriesread, out totalentries);
				if (entriesread > 0)
				{
					IntPtr pItem = pBuf;
					for (int i = 0; i < entriesread; ++i)
					{
						var groupinfo = (LOCALGROUP_USERS_INFO_0)Marshal.PtrToStructure(pItem, typeof(LOCALGROUP_USERS_INFO_0));
						pItem = new IntPtr(pItem.ToInt64() + Marshal.SizeOf(typeof(LOCALGROUP_USERS_INFO_0)));
						groups.Add(groupinfo.lgrui0_name);
					}
				}
				netapi32.NetApiBufferFree(pBuf);
			}
			catch (Exception ex) { TraceLogger.Instance.WriteException(ex); throw; }
			return groups.ToArray();
		}

19 View Source File : AccessPolicy.cs
License : GNU General Public License v3.0
Project Creator : aiportal

private IEnumerable<MIB_TCPROW_OWNER_PID> EnumTcpConnectionsV4()
		{
			int dwSize = sizeof(int) + Marshal.SizeOf(typeof(MIB_TCPROW_OWNER_PID)) * 100;
			IntPtr hTcpTable = IntPtr.Zero;
			{
				hTcpTable = Marshal.AllocHGlobal(dwSize);
				int ret = iphlpapi.GetExtendedTcpTable(hTcpTable, ref dwSize, true, util.AF_INET, TCP_TABLE_CLreplaced.TCP_TABLE_OWNER_PID_CONNECTIONS, 0);
				if (ret != util.NO_ERROR)
				{
					// retry for new dwSize.
					Marshal.FreeHGlobal(hTcpTable);
					hTcpTable = Marshal.AllocHGlobal(dwSize);
					ret = iphlpapi.GetExtendedTcpTable(hTcpTable, ref dwSize, true, util.AF_INET, TCP_TABLE_CLreplaced.TCP_TABLE_OWNER_PID_CONNECTIONS, 0);
					if (ret != util.NO_ERROR)
					{
						Marshal.FreeHGlobal(hTcpTable);
						throw new Exception("GetExtendedTcpTable return: " + ret);
					}
				}
			}
			{
				MIB_TCPROW_OWNER_PID item = new MIB_TCPROW_OWNER_PID();
				int dwNumEntries = Marshal.ReadInt32(hTcpTable);
				IntPtr pItem = new IntPtr(hTcpTable.ToInt32() + sizeof(int));
				for (int i = 0; i < dwNumEntries; ++i)
				{
					//var item = (MIB_TCPROW_OWNER_PID)Marshal.PtrToStructure(pItem, typeof(MIB_TCPROW_OWNER_PID));
					Marshal.PtrToStructure(pItem, item);
					pItem = new IntPtr(pItem.ToInt64() + Marshal.SizeOf(typeof(MIB_TCPROW_OWNER_PID)));
					yield return item;
				}
				Marshal.FreeHGlobal(hTcpTable);
			}
		}

19 View Source File : ProxySetting.cs
License : GNU General Public License v3.0
Project Creator : 2dust

public static bool SetProxy(string strProxy, string exceptions, int type)
        {
            InternetPerConnOptionList list = new InternetPerConnOptionList();

            int optionCount = 1;
            if (type == 1)
            {
                optionCount = 1;
            }
            else if (type == 2 || type == 4)
            {
                optionCount = Utils.IsNullOrEmpty(exceptions) ? 2 : 3;
            }

            int m_Int = (int)PerConnFlags.PROXY_TYPE_DIRECT;
            PerConnOption m_Option = PerConnOption.INTERNET_PER_CONN_FLAGS;
            if (type == 2)
            {
                m_Int = (int)(PerConnFlags.PROXY_TYPE_DIRECT | PerConnFlags.PROXY_TYPE_PROXY);
                m_Option = PerConnOption.INTERNET_PER_CONN_PROXY_SERVER;
            }
            else if (type == 4)
            {
                m_Int = (int)(PerConnFlags.PROXY_TYPE_DIRECT | PerConnFlags.PROXY_TYPE_AUTO_PROXY_URL);
                m_Option = PerConnOption.INTERNET_PER_CONN_AUTOCONFIG_URL;
            }

            //int optionCount = Utils.IsNullOrEmpty(strProxy) ? 1 : (Utils.IsNullOrEmpty(exceptions) ? 2 : 3);
            InternetConnectionOption[] options = new InternetConnectionOption[optionCount];
            // USE a proxy server ...
            options[0].m_Option = PerConnOption.INTERNET_PER_CONN_FLAGS;
            //options[0].m_Value.m_Int = (int)((optionCount < 2) ? PerConnFlags.PROXY_TYPE_DIRECT : (PerConnFlags.PROXY_TYPE_DIRECT | PerConnFlags.PROXY_TYPE_PROXY));
            options[0].m_Value.m_Int = m_Int;
            // use THIS proxy server
            if (optionCount > 1)
            {
                options[1].m_Option = m_Option;
                options[1].m_Value.m_StringPtr = Marshal.StringToHGlobalAuto(strProxy);
                // except for these addresses ...
                if (optionCount > 2)
                {
                    options[2].m_Option = PerConnOption.INTERNET_PER_CONN_PROXY_BYPreplaced;
                    options[2].m_Value.m_StringPtr = Marshal.StringToHGlobalAuto(exceptions);
                }
            }

            // default stuff
            list.dwSize = Marshal.SizeOf(list);
            list.szConnection = IntPtr.Zero;
            list.dwOptionCount = options.Length;
            list.dwOptionError = 0;


            int optSize = Marshal.SizeOf(typeof(InternetConnectionOption));
            // make a pointer out of all that ...
            IntPtr optionsPtr = Marshal.AllocCoTaskMem(optSize * options.Length);
            // copy the array over into that spot in memory ...
            for (int i = 0; i < options.Length; ++i)
            {
                if (Environment.Is64BitOperatingSystem)
                {
                    IntPtr opt = new IntPtr(optionsPtr.ToInt64() + (i * optSize));
                    Marshal.StructureToPtr(options[i], opt, false);
                }
                else
                {
                    IntPtr opt = new IntPtr(optionsPtr.ToInt32() + (i * optSize));
                    Marshal.StructureToPtr(options[i], opt, false);
                }
            }

            list.options = optionsPtr;

            // and then make a pointer out of the whole list
            IntPtr ipcoListPtr = Marshal.AllocCoTaskMem((int)list.dwSize);
            Marshal.StructureToPtr(list, ipcoListPtr, false);

            // and finally, call the API method!
            int returnvalue = NativeMethods.InternetSetOption(IntPtr.Zero,
               InternetOption.INTERNET_OPTION_PER_CONNECTION_OPTION,
               ipcoListPtr, list.dwSize) ? -1 : 0;
            if (returnvalue == 0)
            {  // get the error codes, they might be helpful
                returnvalue = Marshal.GetLastWin32Error();
            }
            // FREE the data ASAP
            Marshal.FreeCoTaskMem(optionsPtr);
            Marshal.FreeCoTaskMem(ipcoListPtr);
            if (returnvalue > 0)
            {  // throw the error codes, they might be helpful
                //throw new Win32Exception(Marshal.GetLastWin32Error());
            }

            return (returnvalue < 0);
        }

19 View Source File : TcpEngine.cs
License : GNU General Public License v3.0
Project Creator : aiportal

private static IEnumerable<MIB_TCPROW_OWNER_PID> EnumTcpConnectionsV4()
		{
			int dwSize = sizeof(int) + Marshal.SizeOf(typeof(MIB_TCPROW_OWNER_PID)) * 100;
			IntPtr hTcpTable = IntPtr.Zero;
			{
				hTcpTable = Marshal.AllocHGlobal(dwSize);
				int ret = iphlpapi.GetExtendedTcpTable(hTcpTable, ref dwSize, true, util.AF_INET, TCP_TABLE_CLreplaced.TCP_TABLE_OWNER_PID_CONNECTIONS, 0);
				if (ret != util.NO_ERROR)
				{
					// retry for new dwSize.
					Marshal.FreeHGlobal(hTcpTable);
					hTcpTable = Marshal.AllocHGlobal(dwSize);
					ret = iphlpapi.GetExtendedTcpTable(hTcpTable, ref dwSize, true, util.AF_INET, TCP_TABLE_CLreplaced.TCP_TABLE_OWNER_PID_CONNECTIONS, 0);
					if (ret != util.NO_ERROR)
					{
						Marshal.FreeHGlobal(hTcpTable);
						throw new Exception("GetExtendedTcpTable return: " + ret);
					}
				}
			}
			{
				MIB_TCPROW_OWNER_PID item = new MIB_TCPROW_OWNER_PID();
				int dwNumEntries = Marshal.ReadInt32(hTcpTable);
				IntPtr pItem = new IntPtr(hTcpTable.ToInt32() + sizeof(int));
				for (int i = 0; i < dwNumEntries; ++i)
				{
					//var item = (MIB_TCPROW_OWNER_PID)Marshal.PtrToStructure(pItem, typeof(MIB_TCPROW_OWNER_PID));
					Marshal.PtrToStructure(pItem, item);
					pItem = new IntPtr(pItem.ToInt64() + Marshal.SizeOf(typeof(MIB_TCPROW_OWNER_PID)));
					yield return item;
				}
				Marshal.FreeHGlobal(hTcpTable);
			}
		}

19 View Source File : OVRCommon.cs
License : MIT License
Project Creator : absurd-joy

public IntPtr GetPointer(int byteOffset = 0)
	{
		if (byteOffset < 0 || byteOffset >= m_numBytes)
			return IntPtr.Zero;
		return (byteOffset == 0) ? m_ptr : new IntPtr(m_ptr.ToInt64() + byteOffset);
	}

19 View Source File : SharedMemory.cs
License : GNU General Public License v3.0
Project Creator : aiportal

public bool SetData(byte[] data, int millisecondsTimeout = Timeout.Infinite)
		{
			if (data.Length > Capcity)
				throw new ArgumentOutOfRangeException("data", "The data to be stored is too large for the SharedMemory.");

			bool succeed = false;
			this.MutexInvoke(() =>
			{
				Marshal.WriteInt32(this._memory, 4, data.Length);

				IntPtr pData = new IntPtr(this._memory.ToInt64() + 8);
				Marshal.Copy(data, 0, pData, data.Length);

				succeed = true;

			}, millisecondsTimeout);
			return succeed;
		}

19 View Source File : UserManager.cs
License : GNU General Public License v3.0
Project Creator : aiportal

public static string[] GetLocalUserGroups(string username)
		{
			int read;
			int total;
			IntPtr pbuf;

			int ret = netapi.NetUserGetLocalGroups(null, username, 0, 0, out pbuf, -1, out read, out total);
			if (ret != 0)
				throw new Win32Exception(ret);

			List<string> groups = new List<string>();
			if (read > 0)
			{
				var g = new LOCALGROUP_USERS_INFO_0();
				IntPtr pItem = pbuf;
				for (int i = 0; i < read; ++i)
				{
					Marshal.PtrToStructure(pItem, g);
					pItem = new IntPtr(pItem.ToInt64() + Marshal.SizeOf(typeof(LOCALGROUP_USERS_INFO_0)));
					groups.Add(g.name);
				}
			}
			netapi.NetApiBufferFree(pbuf);
			return groups.ToArray();
		}

19 View Source File : NotifyIcon.cs
License : GNU General Public License v3.0
Project Creator : aduskin

private IntPtr Callback(IntPtr hWnd, int msg, IntPtr wparam, IntPtr lparam)
        {
            if (IsLoaded)
            {
                if (msg == _wmTaskbarCreated)
                {
                    UpdateIcon(true);
                }
                else
                {
                    switch (lparam.ToInt64())
                    {
                        case InteropValues.WM_LBUTTONDBLCLK:
                            WmMouseDown(MouseButton.Left, 2);
                            break;
                        case InteropValues.WM_LBUTTONUP:
                            WmMouseUp(MouseButton.Left);
                            break;
                        case InteropValues.WM_RBUTTONUP:
                            ShowContextMenu();
                            WmMouseUp(MouseButton.Right);
                            break;
                        case InteropValues.WM_MOUSEMOVE:
                            if (!_dispatcherTimerPos.IsEnabled)
                            {
                                _dispatcherTimerPos.Interval = TimeSpan.FromMilliseconds(200);
                                _dispatcherTimerPos.Start();
                            }
                            break;
                    }
                }
            }

            return InteropMethods.DefWindowProc(hWnd, msg, wparam, lparam);
        }

19 View Source File : UserManager.cs
License : GNU General Public License v3.0
Project Creator : aiportal

public static IEnumerable<DomainGroup> EnumLocalGroups(bool sid = false)
		{
			int read;
			int total;
			int resume;
			IntPtr buf;

			int ret = netapi.NetLocalGroupEnum(null, 1, out buf, util.MAX_PREFERRED_LENGTH, out read, out total, out resume);
			if (ret != 0)
				throw new Win32Exception(ret);
			if (read > 0)
			{
				DomainGroup group = new DomainGroup();
				var g = new LOCALGROUP_INFO_1();
				IntPtr pItem = buf;
				for (int i = 0; i < read; i++)
				{
					Marshal.PtrToStructure(pItem, g);
					pItem = new IntPtr(pItem.ToInt64() + Marshal.SizeOf(typeof(LOCALGROUP_INFO_1)));

					if (sid)
						group.SID = GetAccountSID(g.name);
					group.Name = g.name;
					group.Comment = g.comment;
					yield return group;
				}
				netapi.NetApiBufferFree(buf);
			}
		}

19 View Source File : Helpers.cs
License : MIT License
Project Creator : 71

internal static void AllowRW(IntPtr address)
        {
            if (IsARM)
                return;

            if (IsWindows)
            {
                if (VirtualProtect(address, new UIntPtr(1), 0x40 /* PAGE_EXECUTE_READWRITE */, out var _))
                    return;

                goto Error;
            }

            long pagesize  = IsLinux ? LinuxGetPageSize() : OsxGetPageSize();
            long start     = address.ToInt64();
            long pagestart = start & -pagesize;

            int buffsize = IntPtr.Size == sizeof(int) ? 6 : 12;

            if (IsLinux && LinuxProtect(new IntPtr(pagestart), (ulong) (start + buffsize - pagestart), 0x7 /* PROT_READ_WRITE_EXEC */) == 0)
                return;
            if (!IsLinux && OsxProtect(new IntPtr(pagestart), (ulong) (start + buffsize - pagestart), 0x7 /* PROT_READ_WRITE_EXEC */) == 0)
                return;

            Error:
            throw new Exception($"Unable to make method memory readable and writable. Error code: {Marshal.GetLastWin32Error()}");
        }

19 View Source File : OffsetManager.cs
License : GNU Affero General Public License v3.0
Project Creator : akira0245

public static void Setup(SigScanner scanner)
    {
        var props = typeof(Offsets).GetProperties(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)
            .Select(i => (prop: i, Attribute: i.GetCustomAttribute<SigAttribute>())).Where(i => i.Attribute != null);

        List<Exception> exceptions = new List<Exception>(100);
        foreach ((PropertyInfo propertyInfo, SigAttribute sigAttribute) in props)
        {
            try
            {
                var sig = sigAttribute.SigString;
                sig = string.Join(' ', sig.Split(new[] { ' ' }, StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries)
                    .Select(i => i == "?" ? "??" : i));

                IntPtr address;
                switch (sigAttribute)
                {
                    case StaticAddressAttribute:
                        address = scanner.GetStaticAddressFromSig(sig);
                        break;
                    case FunctionAttribute:
                        address = scanner.ScanText(sig);
                        break;
                    case OffsetAttribute:
                    {
                        address = scanner.ScanText(sig);
                        address += sigAttribute.Offset;
                        var structure = Marshal.PtrToStructure(address, propertyInfo.PropertyType);
                        propertyInfo.SetValue(null, structure);
                        PluginLog.Information($"[{nameof(OffsetManager)}][{propertyInfo.Name}] {propertyInfo.PropertyType.FullName} {structure}");
                        continue;
                    }
                    default:
                        throw new ArgumentOutOfRangeException();
                }

                address += sigAttribute.Offset;
                propertyInfo.SetValue(null, address);
                PluginLog.Information($"[{nameof(OffsetManager)}][{propertyInfo.Name}] {address.ToInt64():X}");
            }
            catch (Exception e)
            {
                PluginLog.Error(e, $"[{nameof(OffsetManager)}][{propertyInfo?.Name}] failed to find sig : {sigAttribute?.SigString}");
                exceptions.Add(e);
            }
        }

        if (exceptions.Any())
        {
            throw new AggregateException(exceptions);
        }
    }

19 View Source File : Win32Ptr.cs
License : Apache License 2.0
Project Creator : aequabit

public static IntPtr Subtract(this IntPtr ptr, IntPtr val)
        {
            return new IntPtr((int) (ptr.ToInt64() - val.ToInt64()));
        }

19 View Source File : MouseLLHook.cs
License : MIT License
Project Creator : AlexanderPro

public override void ProcessWindowMessage(ref Message m)
        {
            if (m.Msg == _msgIdMouseLL)
            {
                RaiseEvent(MouseLLEvent, new BasicHookEventArgs(m.WParam, m.LParam));

                var msl = (MSLLHOOKSTRUCT)Marshal.PtrToStructure(m.LParam, typeof(MSLLHOOKSTRUCT));
                if (m.WParam.ToInt64() == WM_MOUSEMOVE)
                {
                    RaiseEvent(MouseMove, new MouseEventArgs(MouseButtons.None, 0, msl.pt.X, msl.pt.Y, 0));
                }
                else if (m.WParam.ToInt64() == WM_LBUTTONDOWN)
                {
                    RaiseEvent(MouseDown, new MouseEventArgs(MouseButtons.Left, 0, msl.pt.X, msl.pt.Y, 0));
                }
                else if (m.WParam.ToInt64() == WM_RBUTTONDOWN)
                {
                    RaiseEvent(MouseDown, new MouseEventArgs(MouseButtons.Right, 0, msl.pt.X, msl.pt.Y, 0));
                }
                else if (m.WParam.ToInt64() == WM_LBUTTONUP)
                {
                    RaiseEvent(MouseUp, new MouseEventArgs(MouseButtons.Left, 0, msl.pt.X, msl.pt.Y, 0));
                }
                else if (m.WParam.ToInt64() == WM_RBUTTONUP)
                {
                    RaiseEvent(MouseUp, new MouseEventArgs(MouseButtons.Right, 0, msl.pt.X, msl.pt.Y, 0));
                }
            }
            else if (m.Msg == _msgIdMouseLLHookReplaced)
            {
                RaiseEvent(HookReplaced, EventArgs.Empty);
            }
        }

19 View Source File : StreamIOCallbacks.cs
License : MIT License
Project Creator : 0xC0000054

public unsafe int Write(IntPtr buffer, uint count, uint* bytesWritten)
        {
            if (bytesWritten != null)
            {
                *bytesWritten = 0;
            }

            if (count == 0)
            {
                return HResult.S_OK;
            }

            try
            {
                long offset = 0;
                long remaining = count;

                do
                {
                    int copySize = (int)Math.Min(MaxBufferSize, remaining);

                    Marshal.Copy(new IntPtr(buffer.ToInt64() + offset), this.streamBuffer, 0, copySize);

                    this.stream.Write(this.streamBuffer, 0, copySize);

                    offset += copySize;
                    remaining -= copySize;

                } while (remaining > 0);

                if (bytesWritten != null)
                {
                    *bytesWritten = count;
                }

                return HResult.S_OK;
            }
            catch (Exception ex)
            {
                this.CallbackExceptionInfo = ExceptionDispatchInfo.Capture(ex);
                return ex.HResult;
            }
        }

19 View Source File : MainForm.cs
License : MIT License
Project Creator : AlexGyver

protected override void WndProc(ref Message m)
        {
            const int WM_SYSCOMMAND = 0x112;
            const int SC_MINIMIZE = 0xF020;
            const int SC_CLOSE = 0xF060;

            if (minimizeToTray.Value && m.Msg == WM_SYSCOMMAND && m.WParam.ToInt64() == SC_MINIMIZE)
            {
                SysTrayHideShow();
            }
            else if (minimizeOnClose.Value && m.Msg == WM_SYSCOMMAND && m.WParam.ToInt64() == SC_CLOSE)
            {
                /*
                 * Apparently the user wants to minimize rather than close
                 * Now we still need to check if we're going to the tray or not
                 * 
                 * Note: the correct way to do this would be to send out SC_MINIMIZE,
                 * but since the code here is so simple,
                 * that would just be a waste of time.
                 */
                if (minimizeToTray.Value)
                {
                    SysTrayHideShow();
                }
                else
                {
                    WindowState = FormWindowState.Minimized;
                }
            }
            else
            {
                base.WndProc(ref m);
            }
        }

19 View Source File : AccessPolicy.cs
License : GNU General Public License v3.0
Project Creator : aiportal

private IEnumerable<MIB_TCP6ROW_OWNER_PID> EnumTcpConnectionsV6()
		{
			int dwSize = sizeof(int) + Marshal.SizeOf(typeof(MIB_TCP6ROW_OWNER_PID)) * 100;
			IntPtr hTcpTable = IntPtr.Zero;
			{
				hTcpTable = Marshal.AllocHGlobal(dwSize);
				int ret = iphlpapi.GetExtendedTcpTable(hTcpTable, ref dwSize, true, util.AF_INET6, TCP_TABLE_CLreplaced.TCP_TABLE_OWNER_PID_CONNECTIONS, 0);
				if (ret != util.NO_ERROR)
				{
					// retry for new dwSize.
					Marshal.FreeHGlobal(hTcpTable);
					hTcpTable = Marshal.AllocHGlobal(dwSize);
					ret = iphlpapi.GetExtendedTcpTable(hTcpTable, ref dwSize, true, util.AF_INET6, TCP_TABLE_CLreplaced.TCP_TABLE_OWNER_PID_CONNECTIONS, 0);
					if (ret != util.NO_ERROR)
					{
						Marshal.FreeHGlobal(hTcpTable);
						throw new Exception("GetExtendedTcpTable return: " + ret);
					}
				}
			}
			{
				MIB_TCP6ROW_OWNER_PID item = new MIB_TCP6ROW_OWNER_PID();
				int dwNumEntries = Marshal.ReadInt32(hTcpTable);
				IntPtr pItem = new IntPtr(hTcpTable.ToInt32() + sizeof(int));
				for (int i = 0; i < dwNumEntries; ++i)
				{
					//var item = (MIB_TCP6ROW_OWNER_PID)Marshal.PtrToStructure(pItem, typeof(MIB_TCP6ROW_OWNER_PID));
					Marshal.PtrToStructure(pItem, item);
					pItem = new IntPtr(pItem.ToInt64() + Marshal.SizeOf(typeof(MIB_TCP6ROW_OWNER_PID)));
					yield return item;
				}
				Marshal.FreeHGlobal(hTcpTable);
			}
		}

19 View Source File : Program.cs
License : MIT License
Project Creator : Alexx999

private static List<MemBlock> Unprotect(SafeProcessHandle process, IntPtr address, IntPtr length)
        {
            var page = Environment.SystemPageSize;

            var result = new List<MemBlock>();

            var baseAddr = (address.ToInt64() / page) * page;

            var totalLen = 0UL;

            var currAddr = baseAddr;

            while (true)
            {
                if (VirtualQueryEx(process.DangerousGetHandle(), new IntPtr(currAddr), out var info,
                        Marshal.SizeOf(typeof(MemoryBasicInformation))) == 0)
                {
                    throw new Exception($"Unable to query memory at 0x{currAddr:X16}, error 0x{Marshal.GetLastWin32Error():X8}");
                }

                totalLen += info.RegionSize.ToUInt64();

                if (!IsReadable(info.Protect))
                {
                    if (!VirtualProtectEx(process.DangerousGetHandle(), info.BaseAddress, info.RegionSize, MemoryProtection.ReadOnly, out var origProt))
                    {
                        throw new Exception($"Unable to unprotect memory at 0x{info.BaseAddress.ToInt64():X16}, error 0x{Marshal.GetLastWin32Error():X8}");
                    }
                    result.Add(new MemBlock { Address = info.BaseAddress, Size = info.RegionSize, OriginalProtection = origProt });
                }


                if (totalLen >= (ulong) length.ToInt64())
                {
                    break;
                }
            }

            return result;
        }

19 View Source File : Ryder.Lightweight.cs
License : MIT License
Project Creator : 71

public static byte[] GetJmpBytes(IntPtr destination)
            {
                switch (RuntimeInformation.ProcessArchitecture)
                {
                    case Architecture.Arm:
                        {
                            // LDR PC, [PC, #-4]
                            // $addr
                            byte[] result = new byte[8];

                            result[0] = 0x04;
                            result[1] = 0xF0;
                            result[2] = 0x1F;
                            result[3] = 0xE5;

                            BitConverter.GetBytes(destination.ToInt32()).CopyTo(result, 4);

                            return result;
                        }

                    case Architecture.Arm64:
                        {
                            // LDR PC, [PC, #-4]
                            // $addr
                            byte[] result = new byte[12];

                            result[0] = 0x04;
                            result[1] = 0xF0;
                            result[2] = 0x1F;
                            result[3] = 0xE5;

                            BitConverter.GetBytes(destination.ToInt64()).CopyTo(result, 4);

                            return result;
                        }

                    case Architecture.X64:
                        {
                            // movabs rax,$addr
                            // jmp rax
                            byte[] result = new byte[12];

                            result[0] = 0x48;
                            result[1] = 0xB8;
                            result[10] = 0xFF;
                            result[11] = 0xE0;

                            BitConverter.GetBytes(destination.ToInt64()).CopyTo(result, 2);

                            return result;
                        }

                    case Architecture.X86:
                        {
                            // push $addr
                            // ret
                            byte[] result = new byte[6];

                            result[0] = 0x68;
                            result[5] = 0xC3;

                            BitConverter.GetBytes(destination.ToInt32()).CopyTo(result, 1);

                            return result;
                        }

                    default:
                        throw UnsupportedArchitecture;
                }
            }

19 View Source File : NativeHelpers.cs
License : MIT License
Project Creator : allisterb

[MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static IntPtr Add<T>(this IntPtr start, int index)
        {
            Debug.replacedert(start.ToInt64() >= 0);
            Debug.replacedert(index >= 0);

            unsafe
            {
                if (sizeof(IntPtr) == sizeof(int))
                {
                    // 32-bit path.
                    uint byteLength = (uint)index * (uint)Unsafe.SizeOf<T>();
                    return (IntPtr)(((byte*)start) + byteLength);
                }
                else
                {
                    // 64-bit path.
                    ulong byteLength = (ulong)index * (ulong)Unsafe.SizeOf<T>();
                    return (IntPtr)(((byte*)start) + byteLength);
                }
            }
        }

19 View Source File : WTSEngine.cs
License : GNU General Public License v3.0
Project Creator : aiportal

public static int[] GetActiveSessions()
		{
			List<int> sessions = new List<int>();
			try
			{
				IntPtr pSessions = IntPtr.Zero;
				int count = 0;
				if (wtsapi32.WTSEnumerateSessions(IntPtr.Zero, 0, 1, ref pSessions, ref count))
				{
					IntPtr pSession = pSessions;
					for (int i = 0; i < count; ++i)
					{
						WTS_SESSION_INFO si = (WTS_SESSION_INFO)Marshal.PtrToStructure(pSession, typeof(WTS_SESSION_INFO));
						pSession = new IntPtr(pSession.ToInt64() + Marshal.SizeOf(typeof(WTS_SESSION_INFO)));
						if (si.State == WTS_CONNECTSTATE_CLreplaced.WTSActive)
							sessions.Add(si.SessionId);
					}
					wtsapi32.WTSFreeMemory(pSessions);
				}
			}
			catch (Exception ex) { TraceLogger.Instance.WriteException(ex); throw; }
			return sessions.ToArray();
		}

19 View Source File : nfapinet.cs
License : MIT License
Project Creator : AmazingDM

public static NF_STATUS nf_setRulesEx(NF_RULE_EX[] rules)
        {
            NF_RULE_EX pRule;

            IntPtr ptr = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(NF_RULE_EX)) * rules.Length);

            long longPtr = ptr.ToInt64();
            for (int i = 0; i < rules.Length; i++)
            {
                pRule = rules[i];

                updateAddressLength(ref pRule.localIpAddress);
                updateAddressLength(ref pRule.localIpAddressMask);
                updateAddressLength(ref pRule.remoteIpAddress);
                updateAddressLength(ref pRule.remoteIpAddressMask);

                Marshal.StructureToPtr(pRule, new IntPtr(longPtr), false);

                longPtr += Marshal.SizeOf(typeof(NF_RULE_EX));
            }

            return nf_setRules(ptr, rules.Length);
        }

19 View Source File : HeifStreamWriter.cs
License : GNU Lesser General Public License v3.0
Project Creator : 0xC0000054

protected override void WriteCore(IntPtr data, long count)
        {
            long offset = 0;
            long remaining = count;

            while (remaining > 0)
            {
                int copySize = (int)Math.Min(MaxWriteBufferSize, remaining);

                Marshal.Copy(new IntPtr(data.ToInt64() + offset), this.streamBuffer, 0, copySize);

                this.stream.Write(this.streamBuffer, 0, copySize);

                offset += copySize;
                remaining -= copySize;
            }
        }

19 View Source File : OverlayForm.cs
License : GNU General Public License v2.0
Project Creator : AmanoTooko

private CefEventFlags GetKeyboardModifiers(ref Message m)
    {
      CefEventFlags cefEventFlags = CefEventFlags.None;
      if (this.IsKeyDown(Keys.Shift))
        cefEventFlags |= CefEventFlags.ShiftDown;
      if (this.IsKeyDown(Keys.Control))
        cefEventFlags |= CefEventFlags.ControlDown;
      if (this.IsKeyDown(Keys.Menu))
        cefEventFlags |= CefEventFlags.AltDown;
      if (this.IsKeyToggled(Keys.NumLock))
        cefEventFlags |= CefEventFlags.NumLockOn;
      if (this.IsKeyToggled(Keys.Capital))
        cefEventFlags |= CefEventFlags.CapsLockOn;
      switch ((Keys) (int) m.WParam)
      {
        case Keys.Clear:
        case Keys.NumPad0:
        case Keys.NumPad1:
        case Keys.NumPad2:
        case Keys.NumPad3:
        case Keys.NumPad4:
        case Keys.NumPad5:
        case Keys.NumPad6:
        case Keys.NumPad7:
        case Keys.NumPad8:
        case Keys.NumPad9:
        case Keys.Multiply:
        case Keys.Add:
        case Keys.Subtract:
        case Keys.Decimal:
        case Keys.Divide:
        case Keys.NumLock:
          cefEventFlags |= CefEventFlags.IsKeyPad;
          break;
        case Keys.Return:
          if ((m.LParam.ToInt64() >> 48 & 256L) != 0L)
          {
            cefEventFlags |= CefEventFlags.IsKeyPad;
            break;
          }
          break;
        case Keys.Prior:
        case Keys.Next:
        case Keys.End:
        case Keys.Home:
        case Keys.Left:
        case Keys.Up:
        case Keys.Right:
        case Keys.Down:
        case Keys.Insert:
        case Keys.Delete:
          if ((m.LParam.ToInt64() >> 48 & 256L) == 0L)
          {
            cefEventFlags |= CefEventFlags.IsKeyPad;
            break;
          }
          break;
        case Keys.LWin:
          cefEventFlags |= CefEventFlags.IsLeft;
          break;
        case Keys.RWin:
          cefEventFlags |= CefEventFlags.IsRight;
          break;
        case Keys.Shift:
          if (this.IsKeyDown(Keys.LShiftKey))
          {
            cefEventFlags |= CefEventFlags.IsLeft;
            break;
          }
          cefEventFlags |= CefEventFlags.IsRight;
          break;
        case Keys.Control:
          if (this.IsKeyDown(Keys.LControlKey))
          {
            cefEventFlags |= CefEventFlags.IsLeft;
            break;
          }
          cefEventFlags |= CefEventFlags.IsRight;
          break;
        case Keys.Alt:
          if (this.IsKeyDown(Keys.LMenu))
          {
            cefEventFlags |= CefEventFlags.IsLeft;
            break;
          }
          cefEventFlags |= CefEventFlags.IsRight;
          break;
      }
      return cefEventFlags;
    }

19 View Source File : UserManager.cs
License : GNU General Public License v3.0
Project Creator : aiportal

public static string[] GetLocalGroupMembers(string groupname)
		{
			int read;
			int total;
			int resume;
			IntPtr pbuf;

			int ret = netapi.NetLocalGroupGetMembers(null, groupname, 3, out pbuf, -1, out read, out total, out resume);
			if (ret != 0)
				throw new Win32Exception(ret);

			List<string> members = new List<string>();
			if (read > 0)
			{
				var m = new LOCALGROUP_MEMBERS_INFO_3();
				IntPtr pItem = pbuf;
				for (int i = 0; i < read; ++i)
				{
					Marshal.PtrToStructure(pItem, m);
					pItem = new IntPtr(pItem.ToInt64() + Marshal.SizeOf(typeof(LOCALGROUP_MEMBERS_INFO_3)));
					members.Add(DomainUser.Parse(m.domainandname).ToString());
				}
			}
			netapi.NetApiBufferFree(pbuf);
			return members.ToArray();
		}

19 View Source File : Native.cs
License : MIT License
Project Creator : 944095635

private static int IntPtrToInt32(IntPtr intPtr)
        {
            return unchecked((int)intPtr.ToInt64());
        }

19 View Source File : HeifStreamReader.cs
License : GNU Lesser General Public License v3.0
Project Creator : 0xC0000054

protected override bool ReadCore(IntPtr data, long count)
        {
            long totalBytesRead = 0;
            long remaining = count;

            while (remaining > 0)
            {
                int streamBytesRead = this.stream.Read(this.streamBuffer, 0, (int)Math.Min(MaxReadBufferSize, remaining));

                if (streamBytesRead == 0)
                {
                    break;
                }

                Marshal.Copy(this.streamBuffer, 0, new IntPtr(data.ToInt64() + totalBytesRead), streamBytesRead);

                totalBytesRead += streamBytesRead;
                remaining -= streamBytesRead;
            }

            return remaining == 0;
        }

19 View Source File : StreamIOCallbacks.cs
License : MIT License
Project Creator : 0xC0000054

public unsafe int Read(IntPtr buffer, uint count, uint* bytesRead)
        {
            if (bytesRead != null)
            {
                *bytesRead = 0;
            }

            if (count == 0)
            {
                return HResult.S_OK;
            }

            try
            {
                long totalBytesRead = 0;
                long remaining = count;

                do
                {
                    int streamBytesRead = this.stream.Read(this.streamBuffer, 0, (int)Math.Min(MaxBufferSize, remaining));

                    if (streamBytesRead == 0)
                    {
                        break;
                    }

                    Marshal.Copy(this.streamBuffer, 0, new IntPtr(buffer.ToInt64() + totalBytesRead), streamBytesRead);

                    totalBytesRead += streamBytesRead;
                    remaining -= streamBytesRead;

                } while (remaining > 0);

                if (bytesRead != null)
                {
                    *bytesRead = (uint)totalBytesRead;
                }
                return HResult.S_OK;
            }
            catch (Exception ex)
            {
                this.CallbackExceptionInfo = ExceptionDispatchInfo.Capture(ex);
                return ex.HResult;
            }
        }

19 View Source File : DynamicInvoke.cs
License : GNU General Public License v3.0
Project Creator : 3xpl01tc0d3r

public static IntPtr GetExportAddress(IntPtr ModuleBase, string ExportName)
        {
            IntPtr FunctionPtr = IntPtr.Zero;
            try
            {
                Int32 PeHeader = Marshal.ReadInt32((IntPtr)(ModuleBase.ToInt64() + 0x3C));
                Int16 OptHeaderSize = Marshal.ReadInt16((IntPtr)(ModuleBase.ToInt64() + PeHeader + 0x14));
                Int64 OptHeader = ModuleBase.ToInt64() + PeHeader + 0x18;
                Int16 Magic = Marshal.ReadInt16((IntPtr)OptHeader);
                Int64 pExport = 0;
                if (Magic == 0x010b)
                {
                    pExport = OptHeader + 0x60;
                }
                else
                {
                    pExport = OptHeader + 0x70;
                }
                Int32 ExportRVA = Marshal.ReadInt32((IntPtr)pExport);
                Int32 OrdinalBase = Marshal.ReadInt32((IntPtr)(ModuleBase.ToInt64() + ExportRVA + 0x10));
                Int32 NumberOfFunctions = Marshal.ReadInt32((IntPtr)(ModuleBase.ToInt64() + ExportRVA + 0x14));
                Int32 NumberOfNames = Marshal.ReadInt32((IntPtr)(ModuleBase.ToInt64() + ExportRVA + 0x18));
                Int32 FunctionsRVA = Marshal.ReadInt32((IntPtr)(ModuleBase.ToInt64() + ExportRVA + 0x1C));
                Int32 NamesRVA = Marshal.ReadInt32((IntPtr)(ModuleBase.ToInt64() + ExportRVA + 0x20));
                Int32 OrdinalsRVA = Marshal.ReadInt32((IntPtr)(ModuleBase.ToInt64() + ExportRVA + 0x24));
                for (int i = 0; i < NumberOfNames; i++)
                {
                    string FunctionName = Marshal.PtrToStringAnsi((IntPtr)(ModuleBase.ToInt64() + Marshal.ReadInt32((IntPtr)(ModuleBase.ToInt64() + NamesRVA + i * 4))));
                    if (FunctionName.Equals(ExportName, StringComparison.OrdinalIgnoreCase))
                    {
                        Int32 FunctionOrdinal = Marshal.ReadInt16((IntPtr)(ModuleBase.ToInt64() + OrdinalsRVA + i * 2)) + OrdinalBase;
                        Int32 FunctionRVA = Marshal.ReadInt32((IntPtr)(ModuleBase.ToInt64() + FunctionsRVA + (4 * (FunctionOrdinal - OrdinalBase))));
                        FunctionPtr = (IntPtr)((Int64)ModuleBase + FunctionRVA);
                        break;
                    }
                }
            }
            catch
            {
                throw new InvalidOperationException("Failed to parse module exports.");
            }

            if (FunctionPtr == IntPtr.Zero)
            {
                throw new MissingMethodException(ExportName + ", export function not found.");
            }
            return FunctionPtr;
        }

19 View Source File : NativeMethods.cs
License : MIT License
Project Creator : ADeltaX

public static int IntPtrToInt32(IntPtr intPtr) => unchecked((int)intPtr.ToInt64());

19 View Source File : WTSEngine.cs
License : GNU General Public License v3.0
Project Creator : aiportal

internal static int[] GetActiveSessions()
		{
			List<int> sessions = new List<int>();
			try
			{
				IntPtr pSessions = IntPtr.Zero;
				int count = 0;
				if (wtsapi32.WTSEnumerateSessions(IntPtr.Zero, 0, 1, ref pSessions, ref count))
				{
					WTS_SESSION_INFO si = new WTS_SESSION_INFO();
					IntPtr p = pSessions;
					for (int i = 0; i < count; ++i)
					{
						Marshal.PtrToStructure(p, si);
						if (si.State == WTS_CONNECTSTATE_CLreplaced.WTSActive)
							sessions.Add(si.SessionId);
						p = new IntPtr(p.ToInt64() + Marshal.SizeOf(typeof(WTS_SESSION_INFO)));
					}
					wtsapi32.WTSFreeMemory(pSessions);
				}
			}
			catch (Exception ex) { TraceLog.WriteException(ex); throw; }
			return sessions.ToArray();
		}

See More Examples