Introduction to unsafe C#: Calling native code and crashing in entirely new ways
summary
Shows how C# can use pointers, fixed and stackalloc to mutate memory (yes even mutating supposedly immutable strings), explain packing/explicit layout and unions, and call native libraries via P/Invoke. Demonstrates building a minimal SQLite wrapper using SafeHandle and NativeMemory/HeapAlloc that works, then reproduces crashes: buffer overflows, dangling delegate kills process when GC collects callback thunks, and fixes via unmanaged function pointers and SafeHandle reference counting. Gives concrete signatures, marshalling notes and platform calling‑convention caveats.
AI-written summary · about
chapters (13)
- 0:00Welcome
- 0:45Why call native code
- 2:12Unsafe C# basics
- 5:23New kinds of bugs
- 9:16Unsafe features & examples
- 15:34Pointer arithmetic
- 21:32Memory layout & struct packing
- 29:39Platform Invoke
- 36:30Calling conventions
- 38:56Safe handles
- 45:42Native callbacks
- 51:44Function pointers
- 54:12Further resources
related talks
06mMy least favorite C++ feature
36mBuilding on an unsafe foundation
01h 01mEmbracing PODs Safely Until They Die
58mC# and Rust: combining managed and unmanaged code without sacrificing safety
44mThis is why we can('t) have nice things
57mDynamic memory allocation challenges in safety critical systems
34mTransitioning to memory safety: lessons from the Android project
58mLeveraging C++20/23 Features for Low Level Interactions
