作为 this 的后续行动问题 我希望有人可以帮助 CredEnumerate应用程序接口(interface)。
据我从文档中了解到,PCREDENTIALS out 参数是一个“指向凭证指针数组的指针”。我能够使用 C# 成功调用 CredEnumerate API,但我不确定如何将 PCREDENTIALS 转换为有用的东西(如凭据列表)。
编辑:这是我正在使用的代码:
int count = 0;
IntPtr pCredentials = IntPtr.Zero;
bool ret = false;
ret = CredEnumerate(null, 0, out count, out pCredentials);
if (ret != false)
{
IntPtr[] credentials = new IntPtr[count];
IntPtr p = pCredentials;
for (int i = 0; i < count; i++)
{
p = new IntPtr(p.ToInt32() + i);
credentials[i] = Marshal.ReadIntPtr(p);
}
List<Credential> creds = new List<Credential>(credentials.Length);
foreach (IntPtr ptr in credentials)
{
creds.Add((Credential)Marshal.PtrToStructure(ptr, typeof(Credential)));
}
}
不幸的是,虽然这适用于数组中的第一个凭据——它被正确生成并添加到列表中——随后的数组项在 Marshal.PtrToStructure 中炸弹并出现以下错误:
试图读取或写入 protected 内存。这通常表明其他内存已损坏。
有什么想法吗?任何人?布勒?
最佳答案
您需要取消引用指向数组的指针以获取数组,然后对于数组中的每个项目您都需要取消引用该项目以获取 PCREDENTIALS
实例。
我找到了 this post with some example code执行你想做的事情:
[DllImport("advapi32", SetLastError = true, CharSet=CharSet.Unicode)]
static extern bool CredEnumerate(string filter, int flag, out int count, out IntPtr
pCredentials);
...
int count = 0;
IntPtr pCredentials = IntPtr.Zero;
IntPtr[] credentials = null;
bool ret = CredEnumerate(null, 0, out count, out pCredentials);
if (ret != false)
{
credentials = new IntPtr[count];
IntPtr p = pCredentials;
for (int n = 0; n < count; n++)
{
credentials[n] = Marshal.ReadIntPtr(pCredentials,
n * Marshal.SizeOf(typeof(IntPtr)));
}
}
else
// failed....
然后对于每个指针,您需要使用 Marshal.PtrToStructure
将指针取消引用到 PCREDENTIALS
结构实例中(抱歉,我找不到 的 typedef PCREDENTIALS
在任何地方,我假设您拥有它 - 如果您确实拥有它,那么在定义它时不要忘记正确的 MarshalAs 属性和 StructLayout 属性):
// assuming you have declared struct PCREDENTIALS
var creds = new List<PCREDENTIALS>(credentials.Length);
foreach (var ptr in credentials)
{
creds.Add((PCREDENTIALS)Marshal.PtrToStructure(ptr, typeof(PCREDENTIALS)));
}
您显然希望结合示例和 PtrToStructure
代码以获得最佳结果,但我想保持示例的完整性。
关于c# - 帮助 CredEnumerate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/254980/