Skip to content

ES CSharp Keyword extern

Codex edited this page Oct 11, 2026 · 2 revisions

Українська · Русский · English · Deutsch · Français · Italiano · Español · 繁體中文 · 日本語 · 한국어

C#: extern

Manual C# · Guía Práctica

Declara un miembro implementado fuera del código C#; típico de la interoperabilidad nativa a través de DllImport. alias externo especifica un alias de ensamblaje externo.

Ejemplo sencillo (Example.cs)

Guarde este ejemplo por separado como Example.cs. Ejecútelo independientemente de los demás ejemplos de esta página.

Example.cs:

// PROJECT-EXAMPLE
class NativeMethods
{
    [System.Runtime.InteropServices.DllImport("kernel32.dll")]
    public static extern uint GetCurrentProcessId();
}

Solo declaración: este código se compila como biblioteca; llámelo desde Main para ejecutarlo.

Sintaxis

[DllImport(...)] public static extern ReturnType Method(...);

Estos dos ejemplos nativos son para Windows. El nombre de la biblioteca, ABI y la disponibilidad de las funciones dependen de la plataforma; la compilación en sí no comprueba su presencia.

Ejemplo 1: forma básica

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.IO;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;

public static class Program
{
    public static async Task Main(string[] args)
    {
        Console.WriteLine(Native.GetCurrentProcessId());
    }
}
public static class Native { [DllImport("kernel32.dll")] public static extern uint GetCurrentProcessId(); }

Ejemplo 2: otra forma práctica

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.IO;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;

public static class Program
{
    public static async Task Main(string[] args)
    {
        Console.WriteLine(Native.GetTickCount64());
    }
}
public static class Native { [DllImport("kernel32.dll")] public static extern ulong GetTickCount64(); }

Fuente oficial: Microsoft Aprender.

Clone this wiki locally