Files
ThreadPilot/docs/reference/SAFE_WIN32_INTEROP_EXAMPLES.md
T
PrimeBuild-pc c9253f879d Enhance CI/release workflow and app robustness
Add comprehensive CI and release improvements (coverage collection, Codecov upload, SBOM generation), split release workflow into build/smoke-test/release stages with deterministic version resolution, artifact uploads, winget manifest updates and changelog generation. Add a pre-commit hook to block large or unwanted artifacts. Introduce runtime improvements: smoke-test startup mode, improved unhandled/dispatcher/task-exception reporting, ThreadPilotException error codes, single-instance behavior adjustments, and logging enhancements. UI and UX changes include a new Logs tab and LogViewer wiring, DWM title-bar theming helper, navigation serialization/unsaved-changes guard, system-tray update backoff logic, and related viewmodel/service integrations. Also add installer template, helper classes, tests, docs, packaging and build scripts, and minor .gitignore updates.
2026-04-15 22:38:35 +02:00

1.3 KiB

Safe Win32 Interop Examples

This guide provides safe patterns for native interop in ThreadPilot.

1) Prefer SafeHandle for Owned Handles

  • Use SafeHandle-derived types for APIs that return handles.
  • Dispose handles deterministically (using or explicit dispose paths).

2) Enable Error Propagation

  • Use SetLastError = true in declarations where Win32 sets an error code.
  • On failure, inspect Marshal.GetLastWin32Error() and log actionable context.

3) Validate Inputs Before Native Calls

  • Guard pointers, lengths, and IDs.
  • Reject invalid process IDs and empty operation payloads early.

4) Isolate Native Call Boundaries

  • Keep P/Invoke calls inside dedicated helper/service classes.
  • Wrap with typed exceptions at service boundary (ThreadPilotException hierarchy).

5) Example Pattern (Pseudo)

if (processId <= 0)
{
    throw new ArgumentOutOfRangeException(nameof(processId));
}

using SafeProcessHandle handle = NativeMethods.OpenProcess(flags, false, (uint)processId);
if (handle.IsInvalid)
{
    int win32 = Marshal.GetLastWin32Error();
    throw new InvalidOperationException($"OpenProcess failed with Win32 error {win32}.");
}

6) Logging Hygiene

  • Sanitize user-controlled strings before logging.
  • Keep logs structured (event type + process + operation + result).