System.Runtime.InteropServices.Marshal.PtrToStructure(System.IntPtr)

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

555 Examples 7

19 View Source File : MouseHookService.cs
License : MIT License
Project Creator : blish-hud

private int HookCallback(int nCode, IntPtr wParam, IntPtr lParam) {
            if (nCode != 0) return User32.CallNextHookEx(HookType.WH_MOUSE_LL, nCode, wParam, lParam);

            int               eventType  = (int)wParam;
            MOUSELLHOOKSTRUCT hookStruct = Marshal.PtrToStructure<MOUSELLHOOKSTRUCT>(lParam);

            var message = new MouseEventMessage {
                EventType = eventType,
                PointX    = hookStruct.pt.x,
                PointY    = hookStruct.pt.y,
                MouseData = hookStruct.mouseData,
                Flags     = hookStruct.flags,
                Time      = hookStruct.time,
                ExtraInfo = hookStruct.extraInfo
            };

            MouseResponseMessage? response = messageService.SendAndWait<MouseResponseMessage>(message, TimeSpan.FromMilliseconds(CALLBACK_TIMEOUT));

            if (response?.IsHandled == true)
                return 1;
            else
                return User32.CallNextHookEx(HookType.WH_MOUSE_LL, nCode, wParam, lParam);
        }

19 View Source File : SteamVR_RenderModel.cs
License : GNU General Public License v3.0
Project Creator : brandonmousseau

private RenderModel_t MarshalRenderModel(System.IntPtr pRenderModel)
        {
            if ((System.Environment.OSVersion.Platform == System.PlatformID.MacOSX) ||
                (System.Environment.OSVersion.Platform == System.PlatformID.Unix))
            {
                var packedModel = (RenderModel_t_Packed)Marshal.PtrToStructure(pRenderModel, typeof(RenderModel_t_Packed));
                RenderModel_t model = new RenderModel_t();
                packedModel.Unpack(ref model);
                return model;
            }
            else
            {
                return (RenderModel_t)Marshal.PtrToStructure(pRenderModel, typeof(RenderModel_t));
            }
        }

19 View Source File : CustomEffectFactory.cs
License : MIT License
Project Creator : amerkoleci

private int SetterImpl(IntPtr thisPtr, IntPtr dataPtr, int dataSize)
            {
                if (dataPtr == IntPtr.Zero)
                    return Result.Ok.Code;

                var shadow = ToShadow(thisPtr);
                var callback = (ID2D1EffectImpl)shadow.Callback;

                var value = Marshal.PtrToStructure<U>(dataPtr);
                PropertyInfo.SetValue(callback, value);

                return Result.Ok.Code;
            }

19 View Source File : KeyEventArgsExt.cs
License : MIT License
Project Creator : Blacklock

internal static KeyEventArgsExt FromRawDataGlobal(CallbackData data)
        {
            var wParam = data.WParam;
            var lParam = data.LParam;
            var keyboardHookStruct =
                (KeyboardHookStruct) Marshal.PtrToStructure(lParam, typeof(KeyboardHookStruct));

            var keyData = AppendModifierStates((Keys) keyboardHookStruct.VirtualKeyCode);

            var keyCode = (int) wParam;
            var isKeyDown = keyCode == Messages.WM_KEYDOWN || keyCode == Messages.WM_SYSKEYDOWN;
            var isKeyUp = keyCode == Messages.WM_KEYUP || keyCode == Messages.WM_SYSKEYUP;

            const uint maskExtendedKey = 0x1;
            var isExtendedKey = (keyboardHookStruct.Flags & maskExtendedKey) > 0;

            return new KeyEventArgsExt(keyData, keyboardHookStruct.ScanCode, keyboardHookStruct.Time, isKeyDown,
                isKeyUp, isExtendedKey);
        }

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

public static unsafe T[] ReadCompound<T>(
            DatatypeMessage datatype,
            DataspaceMessage dataspace,
            Superblock superblock,
            Span<byte> data,
            Func<FieldInfo, string> getName) where T : struct
        {
            if (datatype.Clreplaced != DatatypeMessageClreplaced.Compound)
                throw new Exception($"This method can only be used for data type clreplaced '{DatatypeMessageClreplaced.Compound}'.");

            var type = typeof(T);
            var fieldInfoMap = new Dictionary<string, FieldProperties>();

            foreach (var fieldInfo in type.GetFields())
            {
                var name = getName(fieldInfo);

                var isNotSupported = H5Utils.IsReferenceOrContainsReferences(fieldInfo.FieldType)
                                  && fieldInfo.FieldType != typeof(string);

                if (isNotSupported)
                    throw new Exception("Nested nullable fields are not supported.");

                fieldInfoMap[name] = new FieldProperties()
                {
                    FieldInfo = fieldInfo,
                    Offset = Marshal.OffsetOf(type, fieldInfo.Name)
                };
            }

            var properties = datatype.Properties
                .Cast<CompoundPropertyDescription>()
                .ToList();

            var sourceOffset = 0UL;
            var sourceRawBytes = data;
            var sourceElementSize = datatype.Size;

            var targetArraySize = H5Utils.CalculateSize(dataspace.DimensionSizes, dataspace.Type);
            var targetArray = new T[targetArraySize];
            var targetElementSize = Marshal.SizeOf<T>();

            for (int i = 0; i < targetArray.Length; i++)
            {
                var targetRawBytes = new byte[targetElementSize];
                var stringMap = new Dictionary<FieldProperties, string>();

                foreach (var property in properties)
                {
                    if (!fieldInfoMap.TryGetValue(property.Name, out var fieldInfo))
                        throw new Exception($"The property named '{property.Name}' in the HDF5 data type does not exist in the provided structure of type '{typeof(T)}'.");

                    var fieldSize = (int)property.MemberTypeMessage.Size;

                    // strings
                    if (fieldInfo.FieldInfo.FieldType == typeof(string))
                    {
                        var sourceIndex = (int)(sourceOffset + property.MemberByteOffset);
                        var sourceIndexEnd = sourceIndex + fieldSize;
                        var targetIndex = fieldInfo.Offset.ToInt64();
                        var value = H5Utils.ReadString(property.MemberTypeMessage, sourceRawBytes[sourceIndex..sourceIndexEnd], superblock);

                        stringMap[fieldInfo] = value[0];
                    }
                    // other value types
                    else
                    {
                        for (uint j = 0; j < fieldSize; j++)
                        {
                            var sourceIndex = sourceOffset + property.MemberByteOffset + j;
                            var targetIndex = fieldInfo.Offset.ToInt64() + j;

                            targetRawBytes[targetIndex] = sourceRawBytes[(int)sourceIndex];
                        }
                    }
                }

                sourceOffset += sourceElementSize;

                fixed (byte* ptr = targetRawBytes.replacedpan())
                {
                    // http://benbowen.blog/post/fun_with_makeref/
                    // https://stackoverflow.com/questions/4764573/why-is-typedreference-behind-the-scenes-its-so-fast-and-safe-almost-magical
                    // Both do not work because struct layout is different with __makeref:
                    // https://stackoverflow.com/questions/1918037/layout-of-net-value-type-in-memory
                    targetArray[i] = Marshal.PtrToStructure<T>(new IntPtr(ptr));

                    foreach (var entry in stringMap)
                    {
                        var reference = __makeref(targetArray[i]);
                        entry.Key.FieldInfo.SetValueDirect(reference, entry.Value);
                    }
                }
            }

            return targetArray;
        }

19 View Source File : Utils.cs
License : MIT License
Project Creator : altskop

public static T FromBytes<T>(byte[] bytes)
        {
            GCHandle gcHandle = GCHandle.Alloc(bytes, GCHandleType.Pinned);
            var data = (T)Marshal.PtrToStructure(gcHandle.AddrOfPinnedObject(), typeof(T));
            gcHandle.Free();
            return data;
        }

19 View Source File : ResolutionHelpers.cs
License : GNU General Public License v3.0
Project Creator : BloodHoundAD

private static async Task<(bool success, WorkstationInfo100 info)> CallNetWkstaGetInfo(string hostname)
        {
            if (!Helpers.CheckPort(hostname, 445))
                return (false, new WorkstationInfo100());

            var wkstaData = IntPtr.Zero;
            var netWkstaTask = Task.Run(() => NetWkstaGetInfo(hostname, 100, out wkstaData));
            if (await Task.WhenAny(Task.Delay(5000), netWkstaTask) != netWkstaTask)
                return (false, new WorkstationInfo100());

            if (netWkstaTask.Result != 0)
                return (false, new WorkstationInfo100());

            try
            {
                var wkstaInfo = Marshal.PtrToStructure<WorkstationInfo100>(wkstaData);
                return (true, wkstaInfo);
            }
            finally
            {
                if (wkstaData != IntPtr.Zero)
                    NetApiBufferFree(wkstaData);
            }
        }

19 View Source File : ScanResult.cs
License : Apache License 2.0
Project Creator : airbus-cert

private IntPtr GetProfilingInfoPtr(IntPtr scanContext)
        {
            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                YR_SCAN_CONTEXT_WIN scan_context = Marshal.PtrToStructure<YR_SCAN_CONTEXT_WIN>(scanContext);
                return scan_context.profiling_info;
            }

            if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
            {
                YR_SCAN_CONTEXT_LINUX scan_context = Marshal.PtrToStructure<YR_SCAN_CONTEXT_LINUX>(scanContext);
                return scan_context.profiling_info;
            }

            if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
            {
                YR_SCAN_CONTEXT_OSX scan_context = Marshal.PtrToStructure<YR_SCAN_CONTEXT_OSX>(scanContext);
                return scan_context.profiling_info;
            }
            return IntPtr.Zero;
        }

19 View Source File : WlanApi.cs
License : MIT License
Project Creator : buscseik

private static Wlan.WlanConnectionNotificationData? ParseWlanConnectionNotification(ref Wlan.WlanNotificationData notifyData)
		{
			int expectedSize = Marshal.SizeOf(typeof(Wlan.WlanConnectionNotificationData));
			if (notifyData.dataSize < expectedSize)
				return null;

			Wlan.WlanConnectionNotificationData connNotifyData =
				(Wlan.WlanConnectionNotificationData)
				Marshal.PtrToStructure(notifyData.dataPtr, typeof(Wlan.WlanConnectionNotificationData));
			if (connNotifyData.wlanReasonCode == Wlan.WlanReasonCode.Success)
			{
				IntPtr profileXmlPtr = new IntPtr(
					notifyData.dataPtr.ToInt64() +
					Marshal.OffsetOf(typeof(Wlan.WlanConnectionNotificationData), "profileXml").ToInt64());
				connNotifyData.profileXml = Marshal.PtrToStringUni(profileXmlPtr);
			}

			return connNotifyData;
		}

19 View Source File : MemoryManager.cs
License : MIT License
Project Creator : Akaion

internal TStructure ReadVirtualMemory<TStructure>(IntPtr baseAddress) where TStructure : struct
        {
            var structureSize = Marshal.SizeOf<TStructure>();
            
            var structureBuffer = Marshal.AllocHGlobal(structureSize);

            if (!ReadProcessMemory(_processHandle, baseAddress, structureBuffer, structureSize, IntPtr.Zero))
            {
                ExceptionHandler.ThrowWin32Exception("Failed to read from a region of virtual memory in the remote process");
            }

            try
            {
                return Marshal.PtrToStructure<TStructure>(structureBuffer);
            }

            finally
            {
                Marshal.FreeHGlobal(structureBuffer);
            }
        }

19 View Source File : PropVariantFacade.cs
License : MIT License
Project Creator : Bassman2

public Guid ToGuid()
        {
            if (this.Value.vt == PropVariantType.VT_ERROR)
            {
                Debug.WriteLine($"VT_ERROR: 0x{this.Value.errorCode:X}");
                return new Guid();
            }

            if (this.Value.vt != PropVariantType.VT_CLSID)
            {
                throw new InvalidOperationException($"ToGuid does not work for value type {this.Value.vt}");
            }

            return (Guid)Marshal.PtrToStructure(this.Value.ptrVal, typeof(Guid));
        }

19 View Source File : AlignedArray.cs
License : GNU General Public License v2.0
Project Creator : ArgusMagnus

protected virtual T GetCore(IntPtr ptr) => Marshal.PtrToStructure<T>(ptr);

19 View Source File : ArgumentConverter.cs
License : MIT License
Project Creator : AlternateLife

public object[] ConvertToObjects(ArgumentsData data)
        {
            var arguments = new object[data.Length];

            for (var i = 0; i < (int) data.Length; i++)
            {
                var address = data.Arguments + Marshal.SizeOf(typeof(ArgumentData)) * i;

                var argument = Marshal.PtrToStructure<ArgumentData>(address);

                arguments[i] = ConvertToObject(argument);
            }

            return arguments;
        }

19 View Source File : MouseEventExtArgs.cs
License : MIT License
Project Creator : Blacklock

internal static MouseEventExtArgs FromRawDataApp(CallbackData data)
        {
            var wParam = data.WParam;
            var lParam = data.LParam;

            var marshalledMouseStruct =
                (AppMouseStruct) Marshal.PtrToStructure(lParam, typeof(AppMouseStruct));
            return FromRawDataUniversal(wParam, marshalledMouseStruct.ToMouseStruct());
        }

19 View Source File : Scanner.cs
License : Apache License 2.0
Project Creator : airbus-cert

private YR_CALLBACK_RESULT HandleMessage(
            IntPtr context,
            int message,
            IntPtr message_data,
            IntPtr user_data)
        {
            if (message == Constants.CALLBACK_MSG_RULE_MATCHING)
            {
                var resultsHandle = GCHandle.FromIntPtr(user_data);
                var results = (List<ScanResult>)resultsHandle.Target;

                YR_RULE rule = Marshal.PtrToStructure<YR_RULE>(message_data);
                results.Add(new ScanResult(context, rule));
            }

            return YR_CALLBACK_RESULT.Continue;
        }

19 View Source File : ResolutionHelpers.cs
License : GNU General Public License v3.0
Project Creator : BloodHoundAD

internal static string ResolveDomainNetbiosToDns(string domainName)
        {
            var key = domainName.ToUpper();
            if (NetbiosDomainNameCache.TryGetValue(key, out var flatName))
                return flatName;

            var computerName = Options.Instance.DomainController ?? GetDomainControllerForDomain(domainName);

            var result = DsGetDcName(computerName, domainName, null, null,
                (uint)(DSGETDCNAME_FLAGS.DS_IS_FLAT_NAME | DSGETDCNAME_FLAGS.DS_RETURN_DNS_NAME),
                out var pDomainControllerInfo);

            try
            {
                if (result == 0)
                {
                    var info = Marshal.PtrToStructure<DOMAIN_CONTROLLER_INFO>(pDomainControllerInfo);
                    flatName = info.DomainName;
                }
            }
            finally
            {
                if (pDomainControllerInfo != IntPtr.Zero)
                    NetApiBufferFree(pDomainControllerInfo);
            }

            NetbiosDomainNameCache.TryAdd(key, flatName);
            return flatName;
        }

19 View Source File : IDWriteGdiInterop.cs
License : MIT License
Project Creator : amerkoleci

public bool ConvertFontToLOGFONT(IDWriteFont font, out LogFont logFont)
        {
            logFont = new LogFont();
            ConvertFontToLOGFONT(font, out var nativeLogFont, out var isSystemFont);
            Marshal.PtrToStructure(nativeLogFont, logFont);
            return isSystemFont;
        }

19 View Source File : Struct.cs
License : GNU General Public License v3.0
Project Creator : BorjaMerino

public static T GetStruct<T>(byte[] data, int offset, int length) where T : struct {
            byte[] buffer = new byte[length];
            Array.Copy(data, offset, buffer, 0, buffer.Length);

            GCHandle handle = GCHandle.Alloc(ConvertEndian<T>(buffer), GCHandleType.Pinned);

            try {
                return Marshal.PtrToStructure<T>(handle.AddrOfPinnedObject());
            } finally {
                handle.Free();
            }
        }

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 : PVMarshaler.cs
License : GNU General Public License v3.0
Project Creator : BRH-Media

public object MarshalNativeToManaged(IntPtr pNativeData)
        {
            MyProps t = MyProps.GetTop(m_Index);

            switch (t.GetStage())
            {
                case 0:
                {
                    // We are just starting a "Unmanaged calling managed"
                    // call.

                    // Caller should have cleared variant before calling
                    // us.  Might be acceptable for types *other* than
                    // IUnknown, String, Blob and StringArray, but it is
                    // still bad design.  We're checking for it, but we
                    // work around it.

                    // Read the 16bit VariantType.

                    // Create an empty managed PropVariant without using
                    // pNativeData.
                    t.m_obj = new PropVariant();

                    // Save the pointer for use in MarshalManagedToNative.
                    t.m_ptr = pNativeData;

                    break;
                }
                case 1:
                {
                    if (t.m_ptr != pNativeData)
                    {
                        // If we get here, we have already received a call
                        // to MarshalManagedToNative where we created an
                        // IntPtr and stored it into t.m_ptr.  But the
                        // value we just got preplaceded here isn't the same
                        // one.  Therefore instead of being the second half
                        // of a "Managed calling unmanaged" (as m_InProcsss
                        // led us to believe) this is really the first half
                        // of a nested "Unmanaged calling managed" (see
                        // Recursion in the comments at the top of this
                        // clreplaced).  Add another layer.
                        MyProps.AddLayer(m_Index);

                        // Try this call again now that we have fixed
                        // m_CurrentProps.
                        return MarshalNativeToManaged(pNativeData);
                    }

                    // This is (probably) the second half of "Managed
                    // calling unmanaged."  However, it could be the first
                    // half of a nested usage of PropVariants.  If it is a
                    // nested, we'll eventually figure that out in case 2.

                    // Copy the data from the native pointer into the
                    // managed object that we received in
                    // MarshalManagedToNative.
                    Marshal.PtrToStructure(pNativeData, t.m_obj);

                    break;
                }
                case 2:
                {
                    // Apparently this is 'part 3' of a 2 part call.  Which
                    // means we are doing a nested call.  Normally we would
                    // catch the fact that this is a nested call with the
                    // (t.m_ptr != pNativeData) check above.  However, if
                    // the same PropVariant instance is being preplaceded thru
                    // again, we end up here.  So, add a layer.
                    MyProps.SplitLayer(m_Index);

                    // Try this call again now that we have fixed
                    // m_CurrentProps.
                    return MarshalNativeToManaged(pNativeData);
                }
                default:
                {
                    Environment.FailFast("Something horrible has " +
                                         "happened, probaby due to " +
                                         "marshaling of nested " +
                                         "PropVariant calls.");
                    break;
                }
            }
            t.StageComplete();

            return t.m_obj;
        }

19 View Source File : CameraMetadataApi.cs
License : Apache License 2.0
Project Creator : andijakl

public bool TryGetValues(IntPtr cameraMetadataHandle,
            CameraMetadataTag tag, List<CameraMetadataValue> resultList)
        {
            IntPtr ndkMetadataHandle = IntPtr.Zero;
            ExternApi.ArImageMetadata_getNdkCameraMetadata(m_NativeSession.SessionHandle,
                cameraMetadataHandle, ref ndkMetadataHandle);

            resultList.Clear();
            NdkCameraMetadata entry = new NdkCameraMetadata();
            NdkCameraStatus status = ExternApi.ACameraMetadata_getConstEntry(ndkMetadataHandle, tag, ref entry);
            if (status != NdkCameraStatus.Ok)
            {
                ARDebug.LogErrorFormat("ACameraMetadata_getConstEntry error with native camera error code: {0}",
                    status);
                return false;
            }

            for (int i = 0; i < entry.Count; i++)
            {
                switch (entry.Type)
                {
                    case NdkCameraMetadataType.Byte:
                        sbyte byteValue = (sbyte)Marshal.PtrToStructure(
                            MarshalingHelper.GetPtrToUnmanagedArrayElement<sbyte>(entry.Value, i),
                            typeof(sbyte));
                        resultList.Add(new CameraMetadataValue(byteValue));
                        break;
                    case NdkCameraMetadataType.Int32:
                        int intValue = (int)Marshal.PtrToStructure(
                            MarshalingHelper.GetPtrToUnmanagedArrayElement<int>(entry.Value, i),
                            typeof(int));
                        resultList.Add(new CameraMetadataValue(intValue));
                        break;
                    case NdkCameraMetadataType.Float:
                        float floatValue = (float)Marshal.PtrToStructure(
                            MarshalingHelper.GetPtrToUnmanagedArrayElement<float>(entry.Value, i),
                            typeof(float));
                        resultList.Add(new CameraMetadataValue(floatValue));
                        break;
                    case NdkCameraMetadataType.Int64:
                        long longValue = (long)Marshal.PtrToStructure(
                            MarshalingHelper.GetPtrToUnmanagedArrayElement<long>(entry.Value, i),
                            typeof(long));
                        resultList.Add(new CameraMetadataValue(longValue));
                        break;
                    case NdkCameraMetadataType.Double:
                        double doubleValue = (double)Marshal.PtrToStructure(
                            MarshalingHelper.GetPtrToUnmanagedArrayElement<double>(entry.Value, i),
                            typeof(double));
                        resultList.Add(new CameraMetadataValue(doubleValue));
                        break;
                    case NdkCameraMetadataType.Rational:
                        CameraMetadataRational rationalValue = (CameraMetadataRational)Marshal.PtrToStructure(
                            MarshalingHelper.GetPtrToUnmanagedArrayElement<CameraMetadataRational>(entry.Value, i),
                            typeof(CameraMetadataRational));
                        resultList.Add(new CameraMetadataValue(rationalValue));
                        break;
                    default:
                        return false;
                }
            }

            return true;
        }

19 View Source File : CameraMetadataApi.cs
License : Apache License 2.0
Project Creator : andijakl

public bool GetAllCameraMetadataTags(IntPtr cameraMetadataHandle, List<CameraMetadataTag> resultList)
        {
            IntPtr ndkMetadataHandle = IntPtr.Zero;
            ExternApi.ArImageMetadata_getNdkCameraMetadata(m_NativeSession.SessionHandle,
                cameraMetadataHandle, ref ndkMetadataHandle);

            IntPtr tagsHandle = IntPtr.Zero;
            int tagsCount = 0;
            NdkCameraStatus status = ExternApi.ACameraMetadata_getAllTags(ndkMetadataHandle, ref tagsCount, ref tagsHandle);
            if (status != NdkCameraStatus.Ok)
            {
                ARDebug.LogErrorFormat("ACameraMetadata_getAllTags error with native camera error code: {0}",
                    status);
                return false;
            }

            for (int i = 0; i < tagsCount; i++)
            {
                resultList.Add((CameraMetadataTag)Marshal.PtrToStructure(
                    MarshalingHelper.GetPtrToUnmanagedArrayElement<int>(tagsHandle, i),
                    typeof(int)));
            }

            return true;
        }

19 View Source File : CompiledRules.cs
License : Apache License 2.0
Project Creator : airbus-cert

private void ExtractData()
        {
            var ruleStruct = Marshal.PtrToStructure<YR_RULES>(BasePtr);
            Rules = ObjRefHelper
                .GetRules(ruleStruct.rules_list_head)
                .Select(rule => new Rule(rule))
                .ToList();
            RuleCount = ruleStruct.num_rules;
            StringsCount = ruleStruct.num_strings;
            NamespacesCount = ruleStruct.num_namespaces;
        }

19 View Source File : Gw2ChatLink.cs
License : MIT License
Project Creator : Archomeda

protected static unsafe T Parse<T>(byte[] chatLinkData, int startIndex = 1) where T : struct
        {
            if (chatLinkData == null)
                throw new ArgumentNullException(nameof(chatLinkData));

            int structSize = Marshal.SizeOf(typeof(T));
            if (chatLinkData.Length < structSize + startIndex)
            {
                // Prevent reading past the buffer by creating a new byte array in which the struct can fit
                byte[] bytes = new byte[structSize];
                Array.Copy(chatLinkData, startIndex, bytes, 0, chatLinkData.Length - startIndex);
                chatLinkData = bytes;
                startIndex = 0;
            }

            fixed (byte* ptr = &chatLinkData[startIndex])
            {
                var intPtr = new IntPtr(ptr);
                return Marshal.PtrToStructure<T>(intPtr)!;
            }
        }

19 View Source File : HijackThread.cs
License : MIT License
Project Creator : Akaion

public void CallFunction(CallDescriptor callDescriptor)
        {
            var completionFlagBuffer = _memory.AllocateBlock(IntPtr.Zero, sizeof(bool), ProtectionType.ReadWrite);

            // Write the shellcode used to perform the function call into a buffer

            var shellcode = replacedembleShellcode(callDescriptor, completionFlagBuffer);

            var shellcodeBuffer = _memory.AllocateBlock(IntPtr.Zero, shellcode.Length, ProtectionType.ReadWrite);

            _memory.WriteBlock(shellcodeBuffer, shellcode);

            _memory.ProtectBlock(shellcodeBuffer, shellcode.Length, ProtectionType.ExecuteRead);

            // Open a handle to the first thread

            var firstThreadHandle = Kernel32.OpenThread(AccessMask.SpecificRightsAll | AccessMask.StandardRightsAll, false, _process.Threads[0].Id);

            if (firstThreadHandle.IsInvalid)
            {
                throw new Win32Exception($"Failed to call OpenThread with error code {Marshal.GetLastWin32Error()}");
            }

            if (callDescriptor.IsWow64Call)
            {
                // Suspend the thread

                if (Kernel32.Wow64SuspendThread(firstThreadHandle) == -1)
                {
                    throw new Win32Exception($"Failed to call Wow64SuspendThread with error code {Marshal.GetLastWin32Error()}");
                }

                // Get the context of the thread

                var threadContext = new Wow64Context {ContextFlags = Wow64ContextFlags.Control};

                if (!Kernel32.Wow64GetThreadContext(firstThreadHandle, ref threadContext))
                {
                    throw new Win32Exception($"Failed to call Wow64GetThreadContext with error code {Marshal.GetLastWin32Error()}");
                }

                // Write the original instruction pointer of the thread into the top of its stack

                threadContext.Esp -= sizeof(int);

                _memory.Write((IntPtr) threadContext.Esp, threadContext.Eip);

                // Overwrite the instruction pointer of the thread with the address of the shellcode

                threadContext.Eip = (int) shellcodeBuffer;

                // Update the context of the thread

                if (!Kernel32.Wow64SetThreadContext(firstThreadHandle, ref threadContext))
                {
                    throw new Win32Exception($"Failed to call Wow64SetThreadContext with error code {Marshal.GetLastWin32Error()}");
                }
            }

            else
            {
                // Suspend the thread

                if (Kernel32.SuspendThread(firstThreadHandle) == -1)
                {
                    throw new Win32Exception($"Failed to call SuspendThread with error code {Marshal.GetLastWin32Error()}");
                }

                // Get the context of the thread

                var threadContext = new Context {ContextFlags = ContextFlags.Control};

                var threadContextBuffer = Marshal.AllocHGlobal(Unsafe.SizeOf<Context>());

                Marshal.StructureToPtr(threadContext, threadContextBuffer, false);

                if (!Kernel32.GetThreadContext(firstThreadHandle, threadContextBuffer))
                {
                    throw new Win32Exception($"Failed to call GetThreadContext with error code {Marshal.GetLastWin32Error()}");
                }

                threadContext = Marshal.PtrToStructure<Context>(threadContextBuffer);

                // Write the original instruction pointer of the thread into the top of its stack

                threadContext.Rsp -= sizeof(long);

                _memory.Write((IntPtr) threadContext.Rsp, threadContext.Rip);

                // Overwrite the instruction pointer of the thread with the address of the shellcode

                threadContext.Rip = (long) shellcodeBuffer;

                Marshal.StructureToPtr(threadContext, threadContextBuffer, false);

                // Update the context of the thread

                if (!Kernel32.SetThreadContext(firstThreadHandle, threadContextBuffer))
                {
                    throw new Win32Exception($"Failed to call SetThreadContext with error code {Marshal.GetLastWin32Error()}");
                }

                Marshal.FreeHGlobal(threadContextBuffer);
            }

            // Send a message to the thread to ensure it executes the shellcode

            if (!User32.PostThreadMessage(_process.Threads[0].Id, MessageType.Null, IntPtr.Zero, IntPtr.Zero))
            {
                throw new Win32Exception($"Failed to call PostThreadMessage with error code {Marshal.GetLastWin32Error()}");
            }

            // Resume the thread

            if (Kernel32.ResumeThread(firstThreadHandle) == -1)
            {
                throw new Win32Exception($"Failed to call ResumeThread with error code {Marshal.GetLastWin32Error()}");
            }

            while (!_memory.Read<bool>(completionFlagBuffer))
            {
                Thread.Sleep(1);
            }

            firstThreadHandle.Dispose();

            _memory.FreeBlock(shellcodeBuffer);

            _memory.FreeBlock(completionFlagBuffer);
        }

19 View Source File : Imports.cs
License : MIT License
Project Creator : b9q

public static bool ReadProcessMemory<T>(IntPtr hProcess, IntPtr lpBaseAddress, out T lpBuffer, out UIntPtr lpNumberOfBytesRead) where T : struct
        {
            var buffer = new byte[Marshal.SizeOf(typeof(T))];
            var result = ReadProcessMemory(hProcess, lpBaseAddress, buffer, out lpNumberOfBytesRead);
            var handle = GCHandle.Alloc(buffer, GCHandleType.Pinned);
            lpBuffer = Marshal.PtrToStructure<T>(handle.AddrOfPinnedObject());
            handle.Free();

            return result;
        }

19 View Source File : Junction.cs
License : GNU General Public License v3.0
Project Creator : Artentus

private static ReparseDataBuffer GetReparseData(string path)
        {
            using SafeFileHandle reparsePointHandle = OpenReparsePoint(path, false);
            IntPtr buffer = Marshal.AllocHGlobal(ReparseDataBuffer.MaximumSize);
            try
            {
                Kernel32.DeviceIOControl(reparsePointHandle, IOControlCode.FsctlGetReparsePoint,
                    IntPtr.Zero, 0, buffer, ReparseDataBuffer.MaximumSize, out _);

                ReparseDataBuffer data = Marshal.PtrToStructure<ReparseDataBuffer>(buffer);
                return data;
            }
            finally
            {
                Marshal.FreeHGlobal(buffer);
            }
        }

19 View Source File : ObjectToByte.cs
License : MIT License
Project Creator : allartprotocol

public static CompiledInstruction fromBytes(byte[] arr)
        {
            CompiledInstruction str = new CompiledInstruction();

            int size = Marshal.SizeOf(str);
            IntPtr ptr = Marshal.AllocHGlobal(size);

            Marshal.Copy(arr, 0, ptr, size);

            str = (CompiledInstruction)Marshal.PtrToStructure(ptr, str.GetType());
            Marshal.FreeHGlobal(ptr);

            return str;
        }

19 View Source File : isteammatchmaking.cs
License : MIT License
Project Creator : benotter

public static gameserveritem_t GetServerDetails(HServerListRequest hRequest, int iServer) {
			InteropHelp.TestIfAvailableClient();
			return (gameserveritem_t)Marshal.PtrToStructure(NativeMethods.ISteamMatchmakingServers_GetServerDetails(hRequest, iServer), typeof(gameserveritem_t));
		}

19 View Source File : CustomScanner.cs
License : Apache License 2.0
Project Creator : airbus-cert

private YR_CALLBACK_RESULT HandleMessage(
            IntPtr context,
            int message,
            IntPtr message_data,
            IntPtr user_data)
        {

            if (message == Constants.CALLBACK_MSG_RULE_MATCHING)
            {
                var resultsHandle = GCHandle.FromIntPtr(user_data);
                var results = (List<ScanResult>)resultsHandle.Target;

                YR_RULE rule = Marshal.PtrToStructure<YR_RULE>(message_data);
                results.Add(new ScanResult(context, rule));
            }

            return YR_CALLBACK_RESULT.Continue;
        }

19 View Source File : KeyPressEventArgsExt.cs
License : MIT License
Project Creator : Blacklock

internal static IEnumerable<KeyPressEventArgsExt> FromRawDataGlobal(CallbackData data)
        {
            var wParam = data.WParam;
            var lParam = data.LParam;

            if ((int) wParam != Messages.WM_KEYDOWN && (int) wParam != Messages.WM_SYSKEYDOWN)
                yield break;

            var keyboardHookStruct =
                (KeyboardHookStruct) Marshal.PtrToStructure(lParam, typeof(KeyboardHookStruct));

            var virtualKeyCode = keyboardHookStruct.VirtualKeyCode;
            var scanCode = keyboardHookStruct.ScanCode;
            var fuState = keyboardHookStruct.Flags;

            if (virtualKeyCode == KeyboardNativeMethods.VK_PACKET)
            {
                var ch = (char) scanCode;
                yield return new KeyPressEventArgsExt(ch, keyboardHookStruct.Time);
            }
            else
            {
                char[] chars;
                KeyboardNativeMethods.TryGetCharFromKeyboardState(virtualKeyCode, scanCode, fuState, out chars);
                if (chars == null) yield break;
                foreach (var current in chars)
                    yield return new KeyPressEventArgsExt(current, keyboardHookStruct.Time);
            }
        }

19 View Source File : StructConverter.cs
License : MIT License
Project Creator : AlternateLife

public static T PointerToStruct<T>(IntPtr pointer, bool freePointer = true)
        {
            var value = Marshal.PtrToStructure<T>(pointer);

            if (freePointer)
            {
                Rage.FreeObject(pointer);
            }

            return value;
        }

19 View Source File : MouseEventExtArgs.cs
License : MIT License
Project Creator : Blacklock

internal static MouseEventExtArgs FromRawDataGlobal(CallbackData data)
        {
            var wParam = data.WParam;
            var lParam = data.LParam;

            var marshalledMouseStruct = (MouseStruct) Marshal.PtrToStructure(lParam, typeof(MouseStruct));
            return FromRawDataUniversal(wParam, marshalledMouseStruct);
        }

19 View Source File : Unicorn.cs
License : MIT License
Project Creator : AeonLucid

public IEnumerable<UcMemRegion> MemRegions()
        {
            var err = UcNative.UcMemRegions(Handle, out var regions, out var count);
            if (err != UcErr.UC_ERR_OK)
            {
                throw new UcException(err);
            }

            var size = Marshal.SizeOf<UcMemRegion>();
            var result = new UcMemRegion[count];

            for (var i = 0; i < count; i++)
            {
                yield return Marshal.PtrToStructure<UcMemRegion>(regions + (i * size));
            }
        }

19 View Source File : WinApiMouseHookManager.cs
License : MIT License
Project Creator : blish-hud

protected override int HookCallback(int nCode, IntPtr wParam, IntPtr lParam) {
            if (nCode != 0) return HookExtern.CallNextHookEx(this.HookType, nCode, wParam, lParam);

            MouseEventArgs mouseEventArgs = new MouseEventArgs((MouseEventType)wParam, Marshal.PtrToStructure<MouseLLHookStruct>(lParam));
            bool           isHandled      = false;

            lock (((IList) this.Handlers).SyncRoot) {
                foreach (HandleMouseInputDelegate handler in this.Handlers) {
                    isHandled = handler(mouseEventArgs);
                    if (isHandled) break;
                }
            }

            if (isHandled)
                return 1;
            else
                return HookExtern.CallNextHookEx(this.HookType, nCode, wParam, lParam);
        }

19 View Source File : MemoryUtil.cs
License : GNU General Public License v3.0
Project Creator : am0nsec

protected T GetStructureFromBlob<T>(Int64 offset) where T : struct {
            Span<byte> bytes = this.GetStructureBytesFromOffset<T>(offset);
            if (Marshal.SizeOf<T>() != bytes.Length)
                return default;

            IntPtr ptr = Marshal.AllocHGlobal(Marshal.SizeOf<T>());
            Marshal.Copy(bytes.ToArray(), 0, ptr, bytes.Length);
            T s = Marshal.PtrToStructure<T>(ptr);

            Marshal.FreeHGlobal(ptr);
            return s;
        }

19 View Source File : ResolutionHelpers.cs
License : GNU General Public License v3.0
Project Creator : BloodHoundAD

private static string GetDomainControllerForDomain(string domainName)
        {
            var key = domainName.ToUpper();
            if (DomainControllerCache.TryGetValue(key, out var domainController))
                return domainController;

            var result = DsGetDcName(null, domainName, null, null, (uint)DSGETDCNAME_FLAGS.DS_DIRECTORY_SERVICE_PREFERRED,
                out var pDomainControllerInfo);

            try
            {
                if (result == 0)
                {
                    var info = Marshal.PtrToStructure<DOMAIN_CONTROLLER_INFO>(pDomainControllerInfo);
                    domainController = info.DomainControllerName;
                }
            }
            finally
            {
                if (pDomainControllerInfo != IntPtr.Zero)
                    NetApiBufferFree(pDomainControllerInfo);
            }


            DomainControllerCache.TryAdd(key, domainController);
            return domainController;
        }

19 View Source File : ScanResult.cs
License : Apache License 2.0
Project Creator : airbus-cert

private IntPtr GetMatchesPtr(IntPtr scanContext)
        {
            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                YR_SCAN_CONTEXT_WIN scan_context = Marshal.PtrToStructure<YR_SCAN_CONTEXT_WIN>(scanContext);
                return scan_context.matches;
            }

            if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
            {
                YR_SCAN_CONTEXT_LINUX scan_context = Marshal.PtrToStructure<YR_SCAN_CONTEXT_LINUX>(scanContext);
                return scan_context.matches;
            }

            if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
            {
                YR_SCAN_CONTEXT_OSX scan_context = Marshal.PtrToStructure<YR_SCAN_CONTEXT_OSX>(scanContext);
                return scan_context.matches;
            }
            return IntPtr.Zero;
        }

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

private void ProcessSizing(ref Message m)
        {
            var windowBounds = Marshal.PtrToStructure<WinApiRectangle>(m.LParam);

            var e = new RectangleEventArgs(windowBounds);
            OnAdjustWindowBounds(e);

            WinApiRectangle adjustedWindowBounds = e.Rectangle;

            Marshal.StructureToPtr(adjustedWindowBounds, m.LParam, false);
        }

19 View Source File : IDWriteGdiInterop.cs
License : MIT License
Project Creator : amerkoleci

public void ConvertFontFaceToLOGFONT(IDWriteFontFace font, out LogFont logFont)
        {
            logFont = new LogFont();
            ConvertFontFaceToLOGFONT(font, out IntPtr nativeLogFont);
            Marshal.PtrToStructure(nativeLogFont, logFont);
        }

19 View Source File : SteamVR_RenderModel.cs
License : GNU General Public License v3.0
Project Creator : brandonmousseau

RenderModel LoadRenderModel(CVRRenderModels renderModels, string renderModelName, string baseName)
        {
            var pRenderModel = System.IntPtr.Zero;

            EVRRenderModelError error;
            while (true)
            {
                error = renderModels.LoadRenderModel_Async(renderModelName, ref pRenderModel);
                if (error != EVRRenderModelError.Loading)
                    break;

                Sleep();
            }

            if (error != EVRRenderModelError.None)
            {
                Debug.LogError(string.Format("<b>[SteamVR]</b> Failed to load render model {0} - {1}", renderModelName, error.ToString()));
                return null;
            }

            var renderModel = MarshalRenderModel(pRenderModel);

            var vertices = new Vector3[renderModel.unVertexCount];
            var normals = new Vector3[renderModel.unVertexCount];
            var uv = new Vector2[renderModel.unVertexCount];

            var type = typeof(RenderModel_Vertex_t);
            for (int iVert = 0; iVert < renderModel.unVertexCount; iVert++)
            {
                var ptr = new System.IntPtr(renderModel.rVertexData.ToInt64() + iVert * Marshal.SizeOf(type));
                var vert = (RenderModel_Vertex_t)Marshal.PtrToStructure(ptr, type);

                vertices[iVert] = new Vector3(vert.vPosition.v0, vert.vPosition.v1, -vert.vPosition.v2);
                normals[iVert] = new Vector3(vert.vNormal.v0, vert.vNormal.v1, -vert.vNormal.v2);
                uv[iVert] = new Vector2(vert.rfTextureCoord0, vert.rfTextureCoord1);
            }

            int indexCount = (int)renderModel.unTriangleCount * 3;
            var indices = new short[indexCount];
            Marshal.Copy(renderModel.rIndexData, indices, 0, indices.Length);

            var triangles = new int[indexCount];
            for (int iTri = 0; iTri < renderModel.unTriangleCount; iTri++)
            {
                triangles[iTri * 3 + 0] = (int)indices[iTri * 3 + 2];
                triangles[iTri * 3 + 1] = (int)indices[iTri * 3 + 1];
                triangles[iTri * 3 + 2] = (int)indices[iTri * 3 + 0];
            }

            var mesh = new Mesh();
            mesh.vertices = vertices;
            mesh.normals = normals;
            mesh.uv = uv;
            mesh.triangles = triangles;

#if (UNITY_5_4 || UNITY_5_3 || UNITY_5_2 || UNITY_5_1 || UNITY_5_0)
            mesh.Optimize();
#endif
            //mesh.hideFlags = HideFlags.DontUnloadUnusedreplacedet;

            // Check cache before loading texture.
            var material = materials[renderModel.diffuseTextureId] as Material;
            if (material == null || material.mainTexture == null)
            {
                var pDiffuseTexture = System.IntPtr.Zero;

                while (true)
                {
                    error = renderModels.LoadTexture_Async(renderModel.diffuseTextureId, ref pDiffuseTexture);
                    if (error != EVRRenderModelError.Loading)
                        break;

                    Sleep();
                }

                if (error == EVRRenderModelError.None)
                {
                    var diffuseTexture = MarshalRenderModel_TextureMap(pDiffuseTexture);
                    var texture = new Texture2D(diffuseTexture.unWidth, diffuseTexture.unHeight, TextureFormat.RGBA32, false);
                    if (SystemInfo.graphicsDeviceType == UnityEngine.Rendering.GraphicsDeviceType.Direct3D11)
                    {
                        texture.Apply();
                        System.IntPtr texturePointer = texture.GetNativeTexturePtr();
                        while (true)
                        {
                            error = renderModels.LoadIntoTextureD3D11_Async(renderModel.diffuseTextureId, texturePointer);
                            if (error != EVRRenderModelError.Loading)
                                break;

                            Sleep();
                        }
                    }
                    else
                    {
                        var textureMapData = new byte[diffuseTexture.unWidth * diffuseTexture.unHeight * 4]; // RGBA
                        Marshal.Copy(diffuseTexture.rubTextureMapData, textureMapData, 0, textureMapData.Length);

                        var colors = new Color32[diffuseTexture.unWidth * diffuseTexture.unHeight];
                        int iColor = 0;
                        for (int iHeight = 0; iHeight < diffuseTexture.unHeight; iHeight++)
                        {
                            for (int iWidth = 0; iWidth < diffuseTexture.unWidth; iWidth++)
                            {
                                var r = textureMapData[iColor++];
                                var g = textureMapData[iColor++];
                                var b = textureMapData[iColor++];
                                var a = textureMapData[iColor++];
                                colors[iHeight * diffuseTexture.unWidth + iWidth] = new Color32(r, g, b, a);
                            }
                        }

                        texture.SetPixels32(colors);
                        texture.Apply();
                    }

#if UNITY_URP
                    material = new Material(shader != null ? shader : Shader.Find("Universal Render Pipeline/Lit"));
#else
                    material = new Material(shader != null ? shader : Shader.Find("Standard"));
#endif

                    material.mainTexture = texture;
                    //material.hideFlags = HideFlags.DontUnloadUnusedreplacedet;

                    materials[renderModel.diffuseTextureId] = material;

                    renderModels.FreeTexture(pDiffuseTexture);
                }
                else
                {
                    Debug.Log("<b>[SteamVR]</b> Failed to load render model texture for render model " + renderModelName + ". Error: " + error.ToString());
                }
            }

            // Delay freeing when we can since we'll often get multiple requests for the same model right
            // after another (e.g. two controllers or two basestations).
#if UNITY_EDITOR
            if (!Application.isPlaying)
                renderModels.FreeRenderModel(pRenderModel);
            else
#endif
                StartCoroutine(FreeRenderModel(pRenderModel));

            return new RenderModel(mesh, material);
        }

19 View Source File : KeyboardHook.cs
License : MIT License
Project Creator : 20chan

static IntPtr HookCallback(int nCode, IntPtr wParam, IntPtr lParam) {
            if (nCode >= 0) {
                var hookStruct = Marshal.PtrToStructure<KBDLLHOOKSTRUCT>(lParam);

                int vkCode = hookStruct.vkCode;
                int flags = hookStruct.flags;

                if (wParam == (IntPtr)WM_KEYDOWN
                    || (GetSystemKeyEvent && wParam == (IntPtr)WM_SYSKEYDOWN))
                    if (KeyDown?.Invoke(vkCode) == false)
                        return (IntPtr)1;

                if (wParam == (IntPtr)WM_KEYUP
                    || (GetSystemKeyEvent && wParam == (IntPtr)WM_SYSTEMKEYUP))
                    if (KeyUp?.Invoke(vkCode) == false)
                        return (IntPtr)1;
            }

            return CallNextHookEx(_hookID, nCode, wParam, lParam);
        }

19 View Source File : SteamVR_RenderModel.cs
License : GNU General Public License v3.0
Project Creator : brandonmousseau

private RenderModel_TextureMap_t MarshalRenderModel_TextureMap(System.IntPtr pRenderModel)
        {
            if ((System.Environment.OSVersion.Platform == System.PlatformID.MacOSX) ||
                (System.Environment.OSVersion.Platform == System.PlatformID.Unix))
            {
                var packedModel = (RenderModel_TextureMap_t_Packed)Marshal.PtrToStructure(pRenderModel, typeof(RenderModel_TextureMap_t_Packed));
                RenderModel_TextureMap_t model = new RenderModel_TextureMap_t();
                packedModel.Unpack(ref model);
                return model;
            }
            else
            {
                return (RenderModel_TextureMap_t)Marshal.PtrToStructure(pRenderModel, typeof(RenderModel_TextureMap_t));
            }
        }

19 View Source File : CoreWindow.cs
License : MIT License
Project Creator : amwx

protected override IntPtr WndProc(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam)
		{
			switch ((WM)msg)
			{
				case WM.NCCALCSIZE:
					// Follows logic from how to extend window frame + WindowsTerminal + Firefox
					// Windows Terminal only handles WPARAM = TRUE & only adjusts the top of the
					// rgrc[0] RECT & gets the correct result
					// Firefox, on the other hand, handles BOTH times WM_NCCALCSIZE is called,
					// and modifies the RECT.
					// This particularly differs from the "built-in" method in Avalonia in that
					// I retain the SystemBorder & ability resize the window in the transparent
					// area over the drop shadows, meaning resize handles don't overlap the window

					if (wParam != IntPtr.Zero)
					{
						var ncParams = Marshal.PtrToStructure<NCCALCSIZE_PARAMS>(lParam);

						var originalTop = ncParams.rgrc[0].top;

						var ret = Win32Interop.DefWindowProc(hWnd, (uint)WM.NCCALCSIZE, wParam, lParam);
						if (ret != IntPtr.Zero)
							return ret;

						var newSize = ncParams.rgrc[0];
						newSize.top = originalTop;

						if (WindowState == WindowState.Maximized)
						{
							newSize.top += GetResizeHandleHeight();
						}

						newSize.left += 8;
						newSize.right -= 8;
						newSize.bottom -= 8;

						ncParams.rgrc[0] = newSize;

						Marshal.StructureToPtr(ncParams, lParam, true);

						return IntPtr.Zero;
					}

					return IntPtr.Zero;

				case WM.NCHITTEST:
					return HandleNCHitTest(lParam);

				case WM.SIZE:
					EnsureExtended();
					break;

				case WM.NCMOUSEMOVE:
					if (_fakingMaximizeButton)
					{
						var point = PointToClient(PointFromLParam(lParam));
						_owner.FakeMaximizeHover(_owner.HitTestMaximizeButton(point));
						return IntPtr.Zero;
					}
					break;

				case WM.NCLBUTTONDOWN:
					if (_fakingMaximizeButton)
					{
						var point = PointToClient(PointFromLParam(lParam));
						_owner.FakeMaximizePressed(_owner.HitTestMaximizeButton(point));
						_wasFakeMaximizeDown = true;

						// This is important. If we don't tell the System we've handled this, we'll get that
						// clreplacedic Win32 button showing when we mouse press, and that's not good
						return IntPtr.Zero;
					}
					break;

				case WM.NCLBUTTONUP:
					if (_fakingMaximizeButton && _wasFakeMaximizeDown)
					{
						var point = PointToClient(PointFromLParam(lParam));
						_owner.FakeMaximizePressed(false);
						_wasFakeMaximizeDown = false;
						_owner.FakeMaximizeClick();
						return IntPtr.Zero;
					}
					break;
			}

			return base.WndProc(hWnd, msg, wParam, lParam);
		}

19 View Source File : CreateThread.cs
License : MIT License
Project Creator : Akaion

public void CallFunction(CallDescriptor callDescriptor)
        {
            // Write the shellcode used to perform the function call into a buffer

            var shellcode = replacedembleShellcode(callDescriptor);

            var shellcodeBuffer = _memory.AllocateBlock(IntPtr.Zero, shellcode.Length, ProtectionType.ReadWrite);

            _memory.WriteBlock(shellcodeBuffer, shellcode);

            _memory.ProtectBlock(shellcodeBuffer, shellcode.Length, ProtectionType.ExecuteRead);

            // Create a suspended thread with a spoofed start address

            var ntStatus = Ntdll.NtCreateThreadEx(out var threadHandle, AccessMask.SpecificRightsAll | AccessMask.StandardRightsAll, IntPtr.Zero, _process.SafeHandle, _process.MainModule.BaseAddress, IntPtr.Zero, ThreadCreationFlags.CreateSuspended | ThreadCreationFlags.HideFromDebugger, 0, 0, 0, IntPtr.Zero);

            if (ntStatus != NtStatus.Success)
            {
                throw new Win32Exception($"Failed to call NtCreateThreadEx with error code {ntStatus}");
            }

            if (callDescriptor.IsWow64Call)
            {
                // Get the context of the thread

                var threadContext = new Wow64Context {ContextFlags = Wow64ContextFlags.Integer};

                if (!Kernel32.Wow64GetThreadContext(threadHandle, ref threadContext))
                {
                    throw new Win32Exception($"Failed to call Wow64GetThreadContext with error code {Marshal.GetLastWin32Error()}");
                }

                // Change the spoofed start address to the address of the shellcode

                threadContext.Eax = (int) shellcodeBuffer;

                // Update the context of the thread

                if (!Kernel32.Wow64SetThreadContext(threadHandle, ref threadContext))
                {
                    throw new Win32Exception($"Failed to call Wow64GetThreadContext with error code {Marshal.GetLastWin32Error()}");
                }
            }

            else
            {
                // Get the context of the thread

                var threadContext = new Context {ContextFlags = ContextFlags.Integer};

                var threadContextBuffer = Marshal.AllocHGlobal(Unsafe.SizeOf<Context>());

                Marshal.StructureToPtr(threadContext, threadContextBuffer, false);

                if (!Kernel32.GetThreadContext(threadHandle, threadContextBuffer))
                {
                    throw new Win32Exception($"Failed to call GetThreadContext with error code {Marshal.GetLastWin32Error()}");
                }

                threadContext = Marshal.PtrToStructure<Context>(threadContextBuffer);

                // Change the spoofed start address to the address of the shellcode

                threadContext.Rcx = (long) shellcodeBuffer;

                Marshal.StructureToPtr(threadContext, threadContextBuffer, false);

                // Update the context of the thread

                if (!Kernel32.SetThreadContext(threadHandle, threadContextBuffer))
                {
                    throw new Win32Exception($"Failed to call SetThreadContext with error code {Marshal.GetLastWin32Error()}");
                }

                Marshal.FreeHGlobal(threadContextBuffer);
            }

            // Resume the thread

            if (Kernel32.ResumeThread(threadHandle) == -1)
            {
                throw new Win32Exception($"Failed to call ResumeThread with error code {Marshal.GetLastWin32Error()}");
            }

            if (Kernel32.WaitForSingleObject(threadHandle, int.MaxValue) == -1)
            {
                throw new Win32Exception($"Failed to call WaitForSingleObject with error code {Marshal.GetLastWin32Error()}");
            }

            threadHandle.Dispose();

            _memory.FreeBlock(shellcodeBuffer);
        }

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

protected override void WndProc(ref Message msg)
        {
            base.WndProc(ref msg);
            if (msg.Msg == WM_DEVICECHANGE)
            {
                var msgType = msg.WParam.ToInt32();
                switch (msgType)
                {
                    case DBT_DEVICEARRIVAL:
                    case DBT_DEVICEREMOVECOMPLETE:
                        var hdr = (DEV_BROADCAST_HDR)Marshal.PtrToStructure(msg.LParam, typeof(DEV_BROADCAST_HDR));
                        if (hdr.dbch_devicetype == DBT_DEVTYP_VOLUME)
                        {
                            var vol = (DEV_BROADCAST_VOLUME)msg.GetLParam(typeof(DEV_BROADCAST_VOLUME));
                            if ((vol.dbcv_flags & (DBTF_MEDIA | DBTF_MOUNT_ISO)) != 0)
                            {
                                if (msgType == DBT_DEVICEARRIVAL)
                                {
                                    rescanDiscsButton_Click(null, null);
                                }
                                else
                                {
                                    var dumper = currentDumper;
                                    var driveId = dumper?.Drive.ToDriveId() ?? 0;
                                    if ((vol.dbcv_unitmask & driveId) != 0)
                                    {
                                        if (discBackgroundWorker.IsBusy && !discBackgroundWorker.CancellationPending)
                                        {
                                            dumper.Cts.Cancel();
                                            discBackgroundWorker.CancelAsync();
                                        }
                                        ResetForm();
                                    }
                                }
                            }
                        }
                        break;
                }
            }
        }

19 View Source File : DellSmbiosSmi.cs
License : GNU General Public License v3.0
Project Creator : AaronKelley

private static SmiObject ByteArrayToStruct(byte[] array)
        {
            SmiObject message = new SmiObject();

            int size = Marshal.SizeOf(message);
            IntPtr pointer = Marshal.AllocHGlobal(size);

            Marshal.Copy(array, 0, pointer, size);

            message = (SmiObject)Marshal.PtrToStructure(pointer, message.GetType());
            Marshal.FreeHGlobal(pointer);

            return message;
        }

19 View Source File : Compiler.cs
License : Apache License 2.0
Project Creator : airbus-cert

public void HandleError(
            int errorLevel,
            string fileName,
            int lineNumber,
            IntPtr rule,
            string message,
            IntPtr userData)
        {

            var marshaledRule = rule == IntPtr.Zero
                ? new System.Nullable<YR_RULE>()
                : Marshal.PtrToStructure<YR_RULE>(rule);
            var ruleName = marshaledRule.HasValue ? "No Rule" : Marshal.PtrToStringAnsi(marshaledRule.Value.identifier);
            var msg = string.Format("rule {3}, Line {1}, file: {2}: {0}",
                message,
                lineNumber,
                string.IsNullOrWhiteSpace(fileName) ? fileName : "[none]",
                ruleName);

            compilationErrors.Add(msg);
        }

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

private unsafe IntPtr WindowProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
        {
            if (msg == WM_WINDOWPOSCHANGING)
            {
                var windowPos = Marshal.PtrToStructure<WindowPos>(lParam);
                windowPos.hwndInsertAfter = new IntPtr(HWND_BOTTOM);
                windowPos.flags &= ~(uint)SWP_NOZORDER;
                handled = true;
            }

            if (msg == WM_DPICHANGED)
            {
                var handle = new WindowInteropHelper(this).Handle;
                var rc = (Native.Rect*)lParam.ToPointer();
                SetWindowPos(handle, IntPtr.Zero, 0, 0, rc->Right, rc->Left, SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOZORDER);
                handled = true;
            }

            return IntPtr.Zero;
        }

19 View Source File : CertificateSubjectPublicKeyInfoValidator.cs
License : Apache License 2.0
Project Creator : aspnet

private static byte[] ExtractSpkiBlob(X509Certificate2 certificate)
        {
            // Get a native cert_context from the managed X590Certificate2 instance.
            var certContext = (NativeMethods.CERT_CONTEXT)Marshal.PtrToStructure(certificate.Handle, typeof(NativeMethods.CERT_CONTEXT));

            // Pull the CERT_INFO structure from the context.
            var certInfo = (NativeMethods.CERT_INFO)Marshal.PtrToStructure(certContext.pCertInfo, typeof(NativeMethods.CERT_INFO));

            // And finally grab the key information, public key, algorithm and parameters from it.
            NativeMethods.CERT_PUBLIC_KEY_INFO publicKeyInfo = certInfo.SubjectPublicKeyInfo;

            // Now start encoding to ASN1.
            // First see how large the ASN1 representation is going to be.
            UInt32 blobSize = 0;
            var structType = new IntPtr(NativeMethods.X509_PUBLIC_KEY_INFO);
            if (!NativeMethods.CryptEncodeObject(NativeMethods.X509_ASN_ENCODING, structType, ref publicKeyInfo, null, ref blobSize))
            {
                int error = Marshal.GetLastWin32Error();
                throw new Win32Exception(error);
            }

            // Allocate enough space.
            var blob = new byte[blobSize];

            // Finally get the ASN1 representation.
            if (!NativeMethods.CryptEncodeObject(NativeMethods.X509_ASN_ENCODING, structType, ref publicKeyInfo, blob, ref blobSize))
            {
                int error = Marshal.GetLastWin32Error();
                throw new Win32Exception(error);
            }

            return blob;
        }

See More Examples