プラットフォーム呼び出しの例

User32.dll で MessageBox 関数を定義し、引数として単純な文字列を渡して呼び出す例を次に示します。 この例では、DllImportAttribute.CharSet フィールドは Auto に設定されているため、ターゲット プラットフォームで文字の幅と文字列のマーシャリングを決定できます。

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

その他の例については、「プラットフォーム呼び出しによるデータのマーシャリング」を参照してください。

関連項目