gpt4 book ai didi

c# - PInvoke NetLocalGroupGetMembers 遇到 FatalExecutionEngineError

转载 作者:行者123 更新时间:2023-11-30 21:53:20 25 4
gpt4 key购买 nike

我需要在 C# 中使用 win32 NetLocalGroupGetMembers。我找到并测试了三种解决方案。这三个都因 FatalExecutionEngineError 而失败。框架是.net 4.0

这是一个完整的例子:

API 引用:

static class NetworkAPI
{
[DllImport("Netapi32.dll")]
public extern static int NetLocalGroupGetMembers([MarshalAs(UnmanagedType.LPWStr)] string servername, [MarshalAs(UnmanagedType.LPWStr)] string localgroupname, int level, out IntPtr bufptr, int prefmaxlen, out int entriesread, out int totalentries, out int resumehandle);

[DllImport("Netapi32.dll")]
public extern static int NetApiBufferFree(IntPtr Buffer);

// LOCALGROUP_MEMBERS_INFO_1 - Structure for holding members details
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct LOCALGROUP_MEMBERS_INFO_1
{
public int lgrmi1_sid;
public int lgrmi1_sidusage;
public string lgrmi1_name;
}
}

调用函数:

static void Main(string[] args)
{
int EntriesRead;
int TotalEntries;
int Resume;
IntPtr bufPtr;

string groupName = "Administrators";

NetworkAPI.NetLocalGroupGetMembers(null, groupName, 1, out bufPtr, -1, out EntriesRead, out TotalEntries, out Resume);

if (EntriesRead > 0)
{
NetworkAPI.LOCALGROUP_MEMBERS_INFO_1[] Members = new NetworkAPI.LOCALGROUP_MEMBERS_INFO_1[EntriesRead];
IntPtr iter = bufPtr;

// EntriesRead has the correct quantity of members of the group, so the group is found
for (int i = 0; i < EntriesRead; i++)
{
// --------------------------------------------------
// ==> here the FatalExecutionEngineError happens:
Members[i] = (NetworkAPI.LOCALGROUP_MEMBERS_INFO_1)Marshal.PtrToStructure(iter, typeof(NetworkAPI.LOCALGROUP_MEMBERS_INFO_1));
//
// --------------------------------------------------

iter = (IntPtr)((int)iter + Marshal.SizeOf(typeof(NetworkAPI.LOCALGROUP_MEMBERS_INFO_1)));
Console.WriteLine(Members[i].lgrmi1_name);
}
NetworkAPI.NetApiBufferFree(bufPtr);
}
}

最佳答案

我看到以下错误:

  1. 恢复句柄是一个指针。对该参数使用 ref IntPtr resumehandle,并在第一次调用时传递 IntPtr.Zero。或者,如果您不需要使用恢复句柄,则将参数声明为 IntPtr resumehandle 并传递 IntPtr.Zero。有关完整详细信息,请参阅 MSDN 上的功能文档。
  2. 结构的lgrmi1_sid 成员是一个指针。声明如下:public IntPtr lgrmi1_sid
  3. IntPtr 转换为 int 将导致指针在 64 位上被截断。直接在 IntPtr 上使用算术,或者对于旧的 C# 版本转换为 long。前者更好,如下所示:iter += Marshal.SizeOf(typeof(NetworkAPI.LOCALGROUP_MEMBERS_INFO_1));
  4. 您不检查返回值是否有错误。

修复这些错误,您的程序将正确运行。

关于c# - PInvoke NetLocalGroupGetMembers 遇到 FatalExecutionEngineError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33935825/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com