Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix null reference exception when calling GetLParam(...) on a zero pointer #276

Merged
merged 3 commits into from
Apr 7, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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