ActiveDir 範例
更新:2007 年 11 月
這個範例示範如何調整 Managed 物件的預設 Apartment 設定值,此 Managed 物件會將資料傳遞至呼叫 CoInitialize 方法的 Unmanaged 方法。CoInitialize 方法會在單一執行緒 Apartment (STA) 中初始化 COM 程式庫。依照預設,C# 用戶端會在多執行緒 Apartments (MTA) 中初始化,而 Visual Basic 2005 用戶端會初始化為 STA 物件且不需調整。
ActiveDir 範例使用下列 Unmanaged 方法,顯示其原始函式宣告:
從 Dsuiext.dll 匯出 DsBrowseForContainer。
int DsBrowseForContainer(PDSBROWSEINFO pInfo);
在 C# 中,STAThreadAttribute 屬性會建立 STA Apartment。因為 STA 是 Visual Basic 2005 用戶端的預設 Apartment 設定,所以不需要屬性。Marshal.SizeOf 方法會動態地計算 Unmanaged 結構的大小。
下列程式碼範例的原始程式碼是由 .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 );
}
}