DllImport
Learn to call native libraries with DllImport.
What is DllImport?
The DllImport attribute lets you call a method from an unmanaged (native) DLL. This mechanism is called P/Invoke. The declaration looks like this:
[DllImport("user32.dll")] static extern int MessageBox(IntPtr h, string text, string caption, int type);
The runtime automatically converts parameters between managed and unmanaged types. This is the most common way to call Win32 APIs and C libraries from C#.
extern and static
A method marked with DllImport must be static extern. extern says the body is not in C# (it lives in a native library); static means it is called without an instance.
The runtime intercepts the call and routes it to the matching DLL function, marshaling parameters according to conversion rules. So C# code calls a native function as if it were an ordinary method.
Exercise Call abs via DllImport
Add the declaration [DllImport("libc.so.6")] static extern int abs(int n);. In Main call int r = abs(-5); and print it with Console.WriteLine(r);.
Show example solution
int r = abs(-5); Console.WriteLine(r);
Example solution:
using System;
using System.Runtime.InteropServices;
class Program
{
[DllImport("libc.so.6")]
static extern int abs(int n);
static void Main()
{
int r = abs(-5);
Console.WriteLine(r);
}
}
Test yourself
-
What does DllImport enable?
- Native DLL calls
- Generates a new DLL
- Creates threads
- Defines a managed method
Show answer
Native DLL calls — Correct. DllImport calls methods from native DLLs.
-
Complete the DllImport method
[DllImport("user32.dll")] static extern int ____(IntPtr h, string t, string c, int type);Show answer
[DllImport("user32.dll")] static extern int MessageBox(IntPtr h, string t, string c, int type); -
How is a DllImport method declared?
- public virtual
- abstract override
- static extern
- internal static virtual
Show answer
static extern — Correct. DllImport methods are static extern.