ActiveDir のサンプル

このサンプルでは、CoInitialize メソッドを呼び出すアンマネージ メソッドにマネージ オブジェクトからデータを渡す場合に、そのマネージ オブジェクトの既定のアパートメント設定を調整する方法を示します。CoInitialize メソッドは、シングルスレッド アパートメント (STA) の中で COM ライブラリを初期化します。既定で、C# クライアントは、マルチスレッド アパートメント (MTA) で初期化されます。Visual Basic 2005 クライアントは STA オブジェクトとして初期化され、調整する必要はありません。

ActiveDir のサンプルで使用するアンマネージ メソッドとその関数宣言を次に示します。

  • Dsuiext.dll からエクスポートされる DsBrowseForContainer

    int DsBrowseForContainer(PDSBROWSEINFO pInfo);
    

C# の場合は、STAThreadAttribute 属性によって STA アパートメントが作成されます。STA は Visual Basic 2005 クライアントに関する既定のアパートメント設定なので、属性は必要ありません。Marshal.SizeOf メソッドは、アンマネージ構造体のサイズを動的に計算します。

次のコード例のソース コードは、.NET Framework「プラットフォーム呼び出しの技術サンプル」で提供されています。

プロトタイプの宣言

Public Class LibWrap
   ' Declares a managed prototype for the unmanaged function.
   Declare Unicode Function DsBrowseForContainerW Lib "dsuiext.dll" ( _
      ByRef info As DSBrowseInfo ) As Integer
   Public Shared DSBI_ENTIREDIRECTORY As Integer = &H90000
End Class 'LibWrap
public class LibWrap
{
   // Declares a managed prototype for the unmanaged function.
   [ DllImport( "dsuiext.dll", CharSet=CharSet.Unicode )]
   public static extern int DsBrowseForContainerW( ref DSBrowseInfo info );
   public const int DSBI_ENTIREDIRECTORY = 0x00090000;   
}

関数の呼び出し

Class App
   Public Shared MAX_PATH As Integer = 256
   ' The DsBrowseForContainerW method should be called from STA.
   ' STA is the default for Visual Basic 2005 clients, so no explicit
   ' setting is required as it is for C# clients.
   Public Shared Sub Main()
      ' Initializes all members.
      Dim dsbi As New DSBrowseInfo()
      
      Dim status As Integer = LibWrap.DsBrowseForContainerW( dsbi )
   End Sub 'Main
   
End Class 'App
class App
{
   public const int MAX_PATH = 256;
   // Must be marked as STA because the default is MTA. 
   // DsBrowseForContainerW calls CoInitialize, which initializes the 
   // COM library as STA.
   [ STAThread ]
   public static void Main()
   {
      // Initializes all members.
      …
      int status = LibWrap.DsBrowseForContainerW( ref dsbi );
   }
}

参照

概念

各種のマーシャリングのサンプル
プラットフォーム呼び出しのデータ型
マネージ コードでのプロトタイプの作成