Skip to content

Commit

Permalink
Fix null reference exception when calling GetLParam(...) on a zero …
Browse files Browse the repository at this point in the history
…pointer (#276)
  • Loading branch information
Tyrrrz authored Apr 7, 2024
1 parent f5ea351 commit bf0d9c1
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 8 deletions.
15 changes: 8 additions & 7 deletions LightBulb.PlatformInterop/Internal/WndProcMessage.cs
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
using System;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices;

namespace LightBulb.PlatformInterop.Internal;

internal readonly record struct WndProcMessage(uint Id, nint WParam, nint LParam)
{
public T GetLParam<T>() =>
(T?)Marshal.PtrToStructure(LParam, typeof(T))
?? throw new InvalidOperationException(
$"Failed to deserialize WndProc message's lParam to {typeof(T)}."
);
public T? TryGetLParam<T>()
where T : struct =>
// If LParam is zero, marshaling will fail with null reference exception
// https://github.com/Tyrrrz/LightBulb/issues/275
LParam != 0
? Marshal.PtrToStructure<T>(LParam)
: default(T?);
}
2 changes: 1 addition & 1 deletion LightBulb.PlatformInterop/PowerSettingNotification.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ public partial class PowerSettingNotification(nint handle, Guid powerSettingId,
m =>
{
// Filter out other power events
if (m.GetLParam<PowerBroadcastSetting>().PowerSettingId != powerSettingId)
if (m.TryGetLParam<PowerBroadcastSetting>()?.PowerSettingId != powerSettingId)
return;
callback();
Expand Down

0 comments on commit bf0d9c1

Please sign in to comment.