0Pricing
C# Academy · Lesson

Interop basics (P/Invoke) at a glance

Call native functions with P/Invoke: DllImport basics, marshaling strings, SetLastError, and simple Win32 demos (Sleep, GetTickCount64).

Concept & goals

P/Invoke lets C# call functions from native DLLs.

  • Use DllImport to bind a method
  • Choose CharSet and SetLastError when needed
  • Keep signatures simple and accurate

P/Invoke: Sleep

Bind the native function by declaring a managed method with DllImport.

using System;
using System.Runtime.InteropServices;

// Simple P/Invoke call to native Sleep (Windows kernel32)
// Note: This demo may only run on Windows, but it compiles everywhere.
public class Program
{
  [DllImport("kernel32.dll")]
  private static extern void Sleep(uint dwMilliseconds);

  public static void Main(string[] args)
  {
    Console.WriteLine("Sleeping for 200 ms...");
    // Call native function
    Sleep(200);
    Console.WriteLine("Awake!");
  }
}

All lessons in this course

  1. C# scripting (dotnet script), snippets & REPL
  2. Interop basics (P/Invoke) at a glance
  3. CLI ergonomics
← Back to C# Academy