平台调用示例Platform Invoke Examples

以下示例演示如何定义和调用 User32.dll 中的 MessageBox 函数,并将简单字符串作为参数传递。The following examples demonstrate how to define and call the MessageBox function in User32.dll, passing a simple string as an argument. 在这些示例中,DllImportAttribute.CharSet 字段设置为 Auto,以让目标平台确定字符宽度和字符串封送处理。In the examples, the DllImportAttribute.CharSet field is set to Auto to let the target platform determine the character width and string marshaling.

using namespace System::Runtime::InteropServices;

typedef void* HWND;

[DllImport("user32", CharSet=CharSet::Auto)]
extern "C" IntPtr MessageBox(HWND hWnd,
                             String* pText,
                             String* pCaption,
                             unsigned int uType);

void main() 
{
     String* pText = L"Hello World!";
     String* pCaption = L"Platform Invoke Sample";
     MessageBox(0, pText, pCaption, 0);
}
using System;
using System.Runtime.InteropServices;

public class Win32 {
     [DllImport("user32.dll", CharSet=CharSet.Auto)]
     public static extern IntPtr MessageBox(int hWnd, String text,
                     String caption, uint type);
}

public class HelloWorld {
    public static void Main() {
       Win32.MessageBox(0, "Hello World", "Platform Invoke Sample", 0);
    }
}
Imports System.Runtime.InteropServices

Public Class Win32
    Declare Auto Function MessageBox Lib "user32.dll" _
       (ByVal hWnd As Integer, ByVal txt As String, _
       ByVal caption As String, ByVal Typ As Integer) As IntPtr
End Class

Public Class HelloWorld
    Public Shared Sub Main()
        Win32.MessageBox(0, "Hello World", "Platform Invoke Sample", 0)
    End Sub
End Class

有关其他示例,请参阅通过平台调用封送处理数据For additional examples, see Marshaling Data with Platform Invoke.

请参阅See also