如何使用 IDirectoryObject





3.00/5 (1投票)
2002年6月13日
2分钟阅读

79866

781
如何使用 IDirectoryObject 接口而不是使用 IADs (IDispatch) 对象
引言
本文将简要介绍如何在您的 C++ ADSI 应用程序中使用 IDirectoryObject
,而不是使用为脚本客户端设计的 IADs 对象。
为什么选择 IDirectoryObject 而不是 IADs
ADSI(Active Directory Services Interface)是一个不错的 COM 对象集合,为您提供了轻松访问 Active Directory 或其他 LDAP 目录中的对象和属性的功能。大多数程序员在编程时使用继承自 IDispatch
的 IADs 接口,但使用非脚本接口 IDirectoryObject
可以提高性能并改善 C++ 程序员的编码体验(如果您使用脚本语言和/或 Visual Basic,则别无选择,只能使用 IADs 接口)。所有 ADSI 提供程序都必须实现 IADs 和 IDirectoryInterface,因此不妨利用 IDirectoryObject
接口的特性。
IADs 和 IDirectoryObject
之间的主要区别在于,IDirectoryObject
将为您提供对目录的直接网络访问。IADs 使用一个 *属性缓存*,您通过 Get()
、get_*
和 put_*
方法从该缓存中读取和写入属性,并且您必须接受所有数据都使用 VARIANT
数据类型传递的事实。IDirectoryObject
允许您通过单次请求直接读取和写入对象。
示例
这里有三个代码片段执行几乎相同的事情;检索 Active Directory 中具有给定 GUID 的用户的 distinguishedName
属性。示例可以在上方下载。
IADs
VBScript 和 VC++ 中的代码
第一个示例显示一个带有 distinguishedName
的消息框,并用 VBScript 编写。
' VBScript (script_example.vbs)
Dim oObject As IADs
Dim vValue As Variant
Set oObject = GetObject("GC://<GUID=b74488fda7dc9c488de9b4bbcdde341f>")
vValue = oObject.Get("distinguishedName")
此 C++ 示例在控制台中打印 distinguishedName
。
// C++
IADs* pObject;
HRESULT hr;
VARIANT vValue;
hr = ADsGetObject(CComBSTR(
L"GC://<GUID=b74488fda7dc9c488de9b4bbcdde341f>"),
IID_IADs,
(void**)&pObject);
if(SUCCEEDED(hr)) {
hr = pObject->Get(CComBSTR(L"distinguishedName"), &vValue);
if(SUCCEEDED(hr)) {
USES_CONVERSION;
printf("distinguishedName is %s\n", W2A(vValue.bstrVal));
VariantClear(&vValue);
}
pObject->Release();
}
IDirectoryObject
这与上面相同,但现在使用 IDirectoryObject
。更多的代码,但稍微快一点!
IDirectoryObject* pObject;
HRESULT hr;
PADS_ATTR_INFO pAttributeEntries;
LPWSTR ppAttributeNames[] = {L"distinguishedName"};
DWORD dwAttributesReturned = 0;
hr = ADsGetObject(CComBSTR(
L"GC://<GUID=b74488fda7dc9c488de9b4bbcdde341f>"),
IID_IDirectoryObject,
(void**)&pObject);
if(SUCCEEDED(hr)) {
hr = pObject->GetObjectAttributes(ppAttributeNames,
1, // only one attribute to fetch
&pAttributeEntries,
&dwAttributesReturned );
if(SUCCEEDED(hr)) {
if(dwAttributesReturned >0 ) {
printf("distinguishedName is %S\n",
pAttributeEntries->pADsValues[0].CaseIgnoreString);
}
FreeADsMem(pAttributeEntries); // Free up ADSI memory resources
}
pObject->Release();
}
摘要
在 C++(或纯 C)中编程时,尤其是在读取对象的小量或大量属性,或者在读取 IADs 属性缓存默认不缓存的属性时,请使用 IDirectoryObject
。
注释
示例中使用的 GUID 指向 Active Directory 中的一个用户对象,要检索 GUID,请获取 ADSI 对象的 objectGUID
属性。