Fondamenti di P/Invoke
Dichiari e chiami funzioni native usando DllImport e comprenda il marshaling di tipi primitivi, stringhe e struct.
Fondamenti di P/Invoke è una lezione C# Academy gratuita su CoddyKit. Questa è la lezione 1 di 4. Puoi leggere la lezione completa qui gratuitamente — poi esercitati direttamente nel browser con un editor di codice integrato e un tutor IA disponibile 24/7. Fa parte del percorso di apprendimento C# Academy, e i tuoi progressi si sincronizzano tra il web e l'app CoddyKit. Il corso C# Academy include 4 lezioni in totale.
Che cos'è P/Invoke?
Platform Invocation Services (P/Invoke) consente a C# di chiamare funzioni nelle librerie condivise native (.dll su Windows, .so su Linux, .dylib su macOS). È il meccanismo standard per chiamare le API Win32 o qualsiasi libreria con ABI C da .NET.
La prima chiamata P/Invoke
Dichiari la funzione nativa con [DllImport] e specifichi il nome della libreria. Il CLR gestisce la ricerca e il caricamento della libreria e il marshalling degli argomenti.
using System.Runtime.InteropServices;
// Calling MessageBoxW from user32.dll (Windows)
internal static partial class NativeMethods
{
[DllImport("user32.dll",
EntryPoint = "MessageBoxW",
CharSet = CharSet.Unicode,
SetLastError = true)]
internal static extern int MessageBox(
IntPtr hwnd,
string text,
string caption,
uint type);
}
// Call it:
NativeMethods.MessageBox(IntPtr.Zero, "Hello!", "P/Invoke", 0);
// Windows-only — wrap in RuntimeInformation.IsOSPlatform check
// for cross-platform codeChiamare librerie native personalizzate
P/Invoke funziona con qualsiasi funzione esportata in C, non solo con le API del sistema operativo. Crei una libreria nativa, esporti le funzioni con collegamento C e le chiami da C#.
// mymath.h / mymath.c:
// extern "C" double AddNumbers(double a, double b) { return a + b; }
// Compile: gcc -shared -o libmymath.so mymath.c
// C# declaration:
[DllImport("mymath", // libmymath.so / mymath.dll
EntryPoint = "AddNumbers",
CallingConvention = CallingConvention.Cdecl)]
private static extern double AddNumbers(double a, double b);
// Call:
double result = AddNumbers(3.14, 2.72); // 5.86
// .NET resolves the library via:
// 1. Absolute path if provided
// 2. App directory
// 3. OS library path (PATH / LD_LIBRARY_PATH / DYLD_LIBRARY_PATH)Marshalling dei tipi di base
Il CLR esegue automaticamente il marshalling della maggior parte dei tipi primitivi tra le rappresentazioni gestite e native. Conoscere le corrispondenze evita bug difficili da individuare.
// C Type → C# Type
// int (32-bit) → int or System.Int32
// long (64-bit) → long or System.Int64
// float → float
// double → double
// bool → [MarshalAs(UnmanagedType.Bool)] bool
// char* (ANSI) → string (CharSet.Ansi)
// wchar_t* → string (CharSet.Unicode)
// void* → IntPtr
// size_t → UIntPtr
// Example with explicit marshalling:
[DllImport("libc", EntryPoint = "strlen", CharSet = CharSet.Ansi)]
private static extern UIntPtr StrLen(
[MarshalAs(UnmanagedType.LPStr)] string s);
int len = (int)StrLen("hello"); // 5Passaggio di struct al codice nativo
Usi [StructLayout(LayoutKind.Sequential)] per garantire che la struct venga disposta in memoria esattamente come previsto dal codice nativo.
// C struct:
// struct Point { int x; int y; };
// void DrawPoint(struct Point p);
[StructLayout(LayoutKind.Sequential)]
public struct Point
{
public int X;
public int Y;
}
[DllImport("graphics", EntryPoint = "DrawPoint",
CallingConvention = CallingConvention.Cdecl)]
private static extern void DrawPoint(Point p);
// Pass by value:
DrawPoint(new Point { X = 10, Y = 20 });
// Pass by pointer (ref or out):
[DllImport("graphics", EntryPoint = "GetCenter",
CallingConvention = CallingConvention.Cdecl)]
private static extern void GetCenter(out Point center);
GetCenter(out var pt);Gestione degli errori: GetLastWin32Error
Le funzioni dell'API Windows segnalano gli errori tramite GetLastError(). Imposti SetLastError = true in [DllImport] e chiami Marshal.GetLastWin32Error() dopo la chiamata.
[DllImport("kernel32.dll",
EntryPoint = "CreateFileW",
CharSet = CharSet.Unicode,
SetLastError = true)]
private static extern IntPtr CreateFile(
string fileName,
uint desiredAccess,
uint shareMode,
IntPtr securityAttributes,
uint creationDisposition,
uint flagsAndAttributes,
IntPtr templateFile);
const uint GENERIC_READ = 0x80000000;
const uint OPEN_EXISTING = 3;
var handle = CreateFile("test.txt", GENERIC_READ, 0,
IntPtr.Zero, OPEN_EXISTING, 0, IntPtr.Zero);
if (handle == (IntPtr)(-1))
{
int error = Marshal.GetLastWin32Error();
throw new System.ComponentModel.Win32Exception(error);
}Marshalling di stringhe e buffer
Il marshalling delle stringhe richiede particolare attenzione alla codifica e alla gestione della proprietà. Usi StringBuilder per i buffer di output e gli attributi MarshalAs per specificare la codifica.
// Read into a buffer:
[DllImport("kernel32.dll",
EntryPoint = "GetComputerNameW",
CharSet = CharSet.Unicode,
SetLastError = true)]
private static extern bool GetComputerName(
System.Text.StringBuilder lpBuffer,
ref uint nSize);
uint size = 256;
var buffer = new System.Text.StringBuilder((int)size);
if (GetComputerName(buffer, ref size))
Console.WriteLine(buffer.ToString());
// Return a string owned by native code (don't free it):
[DllImport("mylib", CharSet = CharSet.Ansi)]
[return: MarshalAs(UnmanagedType.LPStr)]
private static extern string GetVersion();Puntatori a funzioni e callback
Passi i delegate gestiti come puntatori a funzioni C. Il CLR crea un thunk, ma deve mantenere in vita il delegate (conservando un riferimento), altrimenti il GC lo raccoglierà e il codice nativo andrà in errore.
// C callback signature: typedef int (*Comparer)(const void*, const void*);
// void qsort(void* base, size_t nitems, size_t size, Comparer compar);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate int CompareCallback(IntPtr a, IntPtr b);
[DllImport("libc", CallingConvention = CallingConvention.Cdecl)]
private static extern void QSort(
int[] data, UIntPtr count, UIntPtr size, CompareCallback compare);
// Keep the delegate ALIVE for the duration of the call:
private static readonly CompareCallback _compare =
(a, b) => Marshal.ReadInt32(a).CompareTo(Marshal.ReadInt32(b));
var data = new[] { 5, 2, 8, 1, 3 };
QSort(data, (UIntPtr)data.Length, (UIntPtr)sizeof(int), _compare);API NativeLibrary
La classe NativeLibrary fornisce il caricamento esplicito delle librerie, la risoluzione dei puntatori a funzione e la personalizzazione dei percorsi multipiattaforma: è l'alternativa moderna alla risoluzione automatica dei nomi delle librerie.
using System.Runtime.InteropServices;
// Explicit load:
var handle = NativeLibrary.Load("/usr/lib/libssl.so.3");
// Resolve a function pointer:
var addPtr = NativeLibrary.GetExport(handle, "AddNumbers");
var addFn = Marshal.GetDelegateForFunctionPointer<Func<double,double,double>>(addPtr);
double result = addFn(1.0, 2.0);
// Unload:
NativeLibrary.Free(handle);
// Custom resolver (called when DllImport can't find a library):
NativeLibrary.SetDllImportResolver(typeof(MyNative).Assembly,
(libName, assembly, searchPath) =>
{
if (libName == "mymath")
return NativeLibrary.Load("/opt/mymath/libmymath.so");
return IntPtr.Zero;
});Caso reale: chiamare OpenSSL
Un esempio reale: chiamare da C# la funzione digest SHA-256 di OpenSSL usando P/Invoke.
internal static class OpenSslInterop
{
[DllImport("libssl", CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr EVP_MD_CTX_new();
[DllImport("libssl", CallingConvention = CallingConvention.Cdecl)]
private static extern void EVP_MD_CTX_free(IntPtr ctx);
[DllImport("libssl", CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr EVP_sha256();
[DllImport("libssl", CallingConvention = CallingConvention.Cdecl)]
private static extern int EVP_DigestInit_ex(IntPtr ctx, IntPtr type, IntPtr engine);
// In practice, use System.Security.Cryptography.SHA256 instead:
// var hash = SHA256.HashData(data);
// P/Invoke to OpenSSL is only needed when you require
// non-managed cryptographic operations or specific OpenSSL features
}Verifica rapida
Perché è necessario mantenere in vita un delegate quando lo si passa come callback nativa?
Riepilogo: fondamenti di P/Invoke
Concetti chiave:
- P/Invoke: chiamare funzioni native con ABI C tramite dichiarazioni
[DllImport] - Il CLR esegue automaticamente il marshalling dei tipi primitivi; per stringhe e tipi personalizzati usare l'attributo
[MarshalAs] [StructLayout(LayoutKind.Sequential)]: garantire che il layout in memoria della struct corrisponda a quello previsto dal codice nativo- Impostare
SetLastError = truee chiamareMarshal.GetLastWin32Error()per gestire gli errori Win32 - Mantenere attivi i riferimenti ai delegate quando vengono passati come callback nativi
NativeLibrary: caricamento esplicito, risoluzione e resolver personalizzato per controllare i percorsi su più piattaforme
Domande Frequenti
La lezione «Fondamenti di P/Invoke» è gratuita?
Sì — il testo completo di «Fondamenti di P/Invoke» è gratuito qui sul web. Per esercitarvi in modo interattivo (un editor di codice integrato e un tutor IA 24/7) e sbloccare il resto del corso C# Academy, passa a CoddyKit PRO. Il corso C# Academy include 4 lezioni in totale.
Cosa imparerò in «Fondamenti di P/Invoke»?
Dichiari e chiami funzioni native usando DllImport e comprenda il marshaling di tipi primitivi, stringhe e struct. Eserciti C# Academy con codice pratico che esegui direttamente nel browser, e un tutor IA 24/7 risponde alle tue domande mentre lavori sulla lezione.
Ho bisogno di esperienza per iniziare C# Academy?
Non è richiesta alcuna esperienza precedente. C# Academy su CoddyKit è strutturato per principianti e studenti avanzati, quindi puoi iniziare da qui o dall'inizio e procedere al tuo ritmo. Questa è la lezione 1 di 4.
Quanto tempo richiede la lezione «Fondamenti di P/Invoke»?
La maggior parte delle lezioni CoddyKit richiede circa 5–10 minuti. Ogni lezione è breve e interattiva, quindi fai progressi costanti e riprendi esattamente da dove hai lasciato su web e app.
Posso scrivere ed eseguire codice in questa lezione C# Academy?
Sì. Ogni lezione C# Academy include un editor di codice integrato, quindi scrivi ed esegui codice reale direttamente nel tuo browser e ricevi feedback istantaneo dall'IA — nessuna configurazione locale necessaria.
Tutte le lezioni di questo corso
- Fondamenti di P/Invoke
- LibraryImport e P/Invoke generato dal codice sorgente
- Codice non sicuro, puntatori e buffer fissi
- Interop COM e wrapper richiamabili dal runtime