CallingConvention 列舉

定義

指定呼叫 Unmanaged 程式碼中實作之方法所需的呼叫慣例。

C#
public enum CallingConvention
C#
[System.Serializable]
public enum CallingConvention
C#
[System.Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public enum CallingConvention
繼承
CallingConvention
屬性

欄位

名稱 Description
Cdecl 2

呼叫端會清除堆疊。 這會啟用有 varargs 的呼叫函式,就可用於接受各種數目參數的方法,如 Printf

FastCall 5

不支援這個呼叫慣例。

StdCall 3

被呼叫端會清除堆疊。

ThisCall 4

第一個參數為 this 指標且儲存在 register ECX 中。 其他參數會被推入至堆疊。 這個呼叫慣例是用來呼叫從 Unmanaged DLL 匯出之類別上的方法。

Winapi 1

這個成員實際上不是呼叫慣例,而是使用 默認平臺呼叫慣例

範例

下列範例示範如何套用 Cdecl 呼叫慣例,因為呼叫端會清除堆棧,所以必須使用此慣例。

C#
using System;
using System.Runtime.InteropServices;

internal static class NativeMethods
{
    // C# doesn't support varargs so all arguments must be explicitly defined.
    // CallingConvention.Cdecl must be used since the stack is
    // cleaned up by the caller.

    // int printf( const char *format [, argument]... )

    [DllImport("msvcrt.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
    internal static extern int printf(String format, int i, double d);

    [DllImport("msvcrt.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
    internal static extern int printf(String format, int i, String s);
}

public class App
{
    public static void Main()
    {
        NativeMethods.printf("\nPrint params: %i %f", 99, 99.99);
        NativeMethods.printf("\nPrint params: %i %s", 99, "abcd");
    }
}

備註

一律使用 CallingConvention 列舉,而不是 CALLCONV 列舉,在 Managed 程式代碼中指定呼叫慣例。 後者僅適用於 COM 定義。 列舉 CallingConvention 是由 DllImportAttribute 和中的 System.Reflection.Emit 數個類別用來動態發出平臺叫用簽章。

適用於

產品 版本
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0

另請參閱