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).

Interop basics (P/Invoke) at a glance is a free C# Academy lesson on CoddyKit — lesson 2 of 3. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the C# Academy learning path, one of 3 lessons in the course, and your progress syncs across the web and the CoddyKit app.

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!");
  }
}

Native return values

Match the native signature: here we return an unsigned 64-bit value.

using System;
using System.Runtime.InteropServices;

// Get system uptime (ms) from native function.
public class Program
{
  [DllImport("kernel32.dll")]
  private static extern ulong GetTickCount64();

  public static void Main(string[] args)
  {
    ulong ms = GetTickCount64();
    Console.WriteLine("Uptime (ms): " + ms);
  }
}

Strings & CharSet

Use CharSet.Unicode for wide-string APIs (the “W” versions). Catch runtime errors on unsupported platforms.

using System;
using System.Runtime.InteropServices;

// Demo: marshaling strings to Unicode with CharSet.Unicode.
// On non-Windows environments this may fail at runtime.
public class Program
{
  [DllImport("user32.dll", CharSet = CharSet.Unicode)]
  private static extern int MessageBox(IntPtr hWnd, string text, string caption, uint type);

  public static void Main(string[] args)
  {
    Console.WriteLine("Calling MessageBox (may require Windows GUI)...");
    // 0x00000040 = MB_ICONINFORMATION
    try
    {
      int result = MessageBox(IntPtr.Zero, "Hello from P/Invoke", "Interop", 0x00000040);
      Console.WriteLine("MessageBox returned: " + result);
    }
    catch (Exception ex)
    {
      Console.WriteLine("MessageBox failed at runtime: " + ex.GetType().Name);
    }
  }
}

SetLastError & types

Error handling:

  • For APIs that set GetLastError, add SetLastError=true in DllImport
  • After a failed call, read Marshal.GetLastWin32Error()
  • Prefer exact types: uint vs int, pointers as IntPtr

Interop hygiene

  • Start with simple APIs (no complex structs)
  • Use IntPtr for handles; release with the right native function
  • Avoid GUI calls on headless environments
  • Document platform limits (Windows-only, etc.)

DllImport purpose

Quick check: What does the DllImport attribute do in P/Invoke?

Recap

Recap: Declare native calls with DllImport, match types carefully, pick CharSet for strings, and handle errors via SetLastError and GetLastError when applicable.

Frequently asked questions

Is the “Interop basics (P/Invoke) at a glance” lesson free?

Yes — the full text of “Interop basics (P/Invoke) at a glance” is free to read here on the web, and the C# Academy course includes 3 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the C# Academy course, upgrade to CoddyKit PRO.

What will I learn in “Interop basics (P/Invoke) at a glance”?

Call native functions with P/Invoke: DllImport basics, marshaling strings, SetLastError, and simple Win32 demos (Sleep, GetTickCount64). You practise C# Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start C# Academy?

No prior experience is required. C# Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 3, so you can start here or from the beginning and move at your own pace.

How long does the “Interop basics (P/Invoke) at a glance” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this C# Academy lesson?

Yes. Every C# Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

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