CsWin32 Interop Guide
CsWin32 replaces [DllImport] with source-generated PInvoke.* calls. FEATURE_WINDOWSINTEROP is the compile-time gate; source builds disable it.
Paired skill: cswin32-com covers struct-based COM interop on top of CsWin32 (ComScope<T>, AgileComPointer<T>, delegate* unmanaged vtables, IComIID, CoCreateInstance, manual COM structs not in Win32 metadata). This file covers only the general P/Invoke layer; the COM skill builds on its blittable-signature rules.
Rules
- Replace
[DllImport]withPInvoke.*. Delete old declarations and hand-written structs/enums/constants. - Gate with
#if FEATURE_WINDOWSINTEROP, add runtimeIsWindowscheck inside. Both required. - Use CsWin32 types directly (
HANDLE,HMODULE,HRESULT.S_OK,FILE_FLAGS_AND_ATTRIBUTES, etc.). - Call
PInvoke.*directly — no wrappers. Types flow viaInternalsVisibleTo. - Prefer CsWin32 for Windows APIs. Use
[LibraryImport]only for non-Windows native calls (e.g.libc), guarded with#if NET. - Preserve the old error-handling contract. Check the original
[DllImport]forPreserveSig/SetLastError/BOOL/HRESULTsemantics and reproduce them:PreserveSig=false→.ThrowOnFailure();SetLastError=true+ failedBOOL→throw new Win32Exception(). Silently returning where the old code threw is a behavior change. See cswin32-com's parity table for the COM-side equivalent.
Blittable signatures
CsWin32 is configured with allowMarshaling: false, so every [DllImport] and every manual
COM vtable method must be blittable — no marshalling at the boundary. These rules apply
to both. For COM-vtable-only additions, see
- Return
HRESULTfrom HRESULT-returning APIs (notint). Blittable (singleintfield),
exposes .Succeeded / .Failed / .ThrowOnFailure(). Use HRESULT.S_OK over 0; cast
e.HResult to (HRESULT) when wrapping. AddRef / Release return uint.
- Call
.ThrowOnFailure()instead ofif (hr.Failed) Marshal.ThrowExceptionForHR(hr)—
same exception, IErrorInfo-enriched, one-line call site:
iface->Method(...).ThrowOnFailure();. Branch on hr only when handling a specific HRESULT
(e.g. ERROR_INSUFFICIENT_BUFFER) before throwing. See
for the migration contract.
- Use
PCWSTR/PWSTRfor wide strings, never managedstring. Implicit conversion from
fixed (char* p = managedString). Add to NativeMethods.txt if not yet generated.
T**notout T*for pointer outputs.outtriggers marshaling + afixedround-trip
at every call site.
void*for opaque / reserved params — neverIntPtr.Zero; passnullliterally.
IntPtr is fine at boundaries with the wider .NET surface (Marshal.*,
SafeHandle.DangerousGetHandle, public API).
- Prefer
nint/nuintoverIntPtr/UIntPtrfor native-sized integers — no boxing,
better cast semantics, no IntPtr.Zero ceremony.
- No managed reference types (
string,StringBuilder, arrays) in blittable signatures. - Don't specify
PreserveSig = trueon[DllImport]— it's the default. Use
PreserveSig = false only to force marshaller throw-on-failure (rare; prefer returning
HRESULT and .ThrowOnFailure()). [ComImport] defaults the opposite way, but struct-based
COM uses raw delegate* and isn't affected — see
- Constrain flag / option parameters to a typed
enum. When a nativeDWORD/ULONG/
int is documented as a typedef enum or #define set, declare a C# [Flags] enum Foo : uint
(matching the underlying type) and use it in the signature (and delegate* cast for COM).
Mirror the constraint even when the native side has no named enum. Self-documenting at the
call site: OpenScope(path, CorOpenFlags.ofRead, ...) vs OpenScope(path, 0, ...). Co-locate
the enum next to its consumer. See