Skip to content

KO CSharp Keyword unmanaged function pointer calling convention

Codex edited this page Oct 11, 2026 · 2 revisions

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

C#: unmanaged — 함수 포인터 호출 규칙

핸드북 C# · 실용 가이드

Delegate* 유형의 unmanaged는 관리되지 않는 호출 규칙을 지정합니다. 목록이 없으면 플랫폼 계약이 사용됩니다. Cdecl은 대괄호 안에 명시적으로 지정할 수 있습니다. UnmanagedCallersOnly이 포함된 정적 C# 메서드는 일반 관리 호출 대신 호환되는 관리되지 않는 포인터를 통해 호출됩니다. 이 프로젝트는 안전하지 않은 블록을 허용합니다.

간단한 예제 (Example.cs)

이 예제를 Example.cs로 따로 저장하고 이 페이지의 다른 예제와 독립적으로 실행하세요.

Example.cs:

// PROJECT-EXAMPLE
unsafe
{
    delegate* unmanaged[Cdecl]<int, int> twice = &Tools.Twice;
    System.Console.WriteLine(twice(4));
}
static class Tools { [System.Runtime.InteropServices.UnmanagedCallersOnly(CallConvs = new[] { typeof(System.Runtime.CompilerServices.CallConvCdecl) })] public static int Twice(int value) => value * 2; }

프로젝트에서 <AllowUnsafeBlocks>true</AllowUnsafeBlocks>를 활성화하세요. 포인터는 표시된 범위 내에서만 유효합니다.

결과:

8

통사론

delegate* unmanaged<int, int> operation = &Transform;
delegate* unmanaged[Cdecl]<int, int> callback = &TransformCdecl;

비관리형 플랫폼 계약에 대한 통화

파일 Example.csproj:

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net10.0</TargetFramework>
    <LangVersion>14.0</LangVersion>
    <Nullable>enable</Nullable>
    <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
  </PropertyGroup>

</Project>

파일 Program.cs:

using System;
using System.Runtime.InteropServices;

internal static unsafe class Program
{
    public static void Main()
    {
        delegate* unmanaged<int, int> doubleValue = &DoubleValue;
        Console.WriteLine(doubleValue(12));
    }
    [UnmanagedCallersOnly]
    private static int DoubleValue(int value) => value * 2;
}

결과:

24

명시적으로 지정된 Cdecl 계약이 포함된 콜백

파일 Example.csproj:

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net10.0</TargetFramework>
    <LangVersion>14.0</LangVersion>
    <Nullable>enable</Nullable>
    <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
  </PropertyGroup>

</Project>

파일 Program.cs:

using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

internal static unsafe class Program
{
    public static void Main()
    {
        delegate* unmanaged[Cdecl]<int, int, int> callback = &Difference;
        int result = InvokeCallback(callback, 14, 5);
        Console.WriteLine(result);
    }
    private static int InvokeCallback(delegate* unmanaged[Cdecl]<int, int, int> callback,
        int left, int right) => callback(left, right);
    [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
    private static int Difference(int left, int right) => left - right;
}

결과:

9

공식 출처: Microsoft 학습.

Clone this wiki locally