I have this structure that I am using in conjunction with
NetLocalGroupAd dMembers:
[StructLayout(La youtKind.Sequen tial, CharSet=CharSet .Unicode)]
public struct LOCALGROUP_MEMB ERS_INFO_3
{
[MarshalAs(Unman agedType.LPWStr )] public string lgrmi3_domainan dname;
}
I am having failures that stinky hugely of either memory allocation being
incorrectly sized, or simply using the wrong allocation method. To test
this, I snipped the code somewhat and threw it into nUnit. This is what I
have:
/// <summary>
/// Hammers memory allocation to try to force a failure
/// </summary>
[Test]
public void TestMemoryAlloc ation()
{
System.Console. Write("\n\n");
System.Console. Write("Testing memory issue...\n");
for (int i=1; i<=15; i++)
{
System.Console. Write("Count: "+ i.ToString());
CatchAndRelease ();
System.Console. Write(".\n");
}
}
/// <summary>
/// Allocates and clears memory
/// </summary>
public void CatchAndRelease ()
{
try
{
LOCALGROUP_MEMB ERS_INFO_3 MemberToAdd;
LOCALGROUP_MEMB ERS_INFO_3[] MembersToAdd;
IntPtr bufPtr=IntPtr.Z ero;
// Initialize Variables
MemberToAdd.lgr mi3_domainandna me = "DOMAIN\\USERNA ME";
MembersToAdd = new LOCALGROUP_MEMB ERS_INFO_3[1] { MemberToAdd };
// Allocate memory and convert data into pointer
bufPtr =
Marshal.AllocHG lobal(Marshal.S izeOf(typeof(LO CALGROUP_MEMBER S_INFO_3)) *
MembersToAdd.Le ngth);
Marshal.Structu reToPtr(Members ToAdd[0], bufPtr, true);
// Free memory and zero out the pointer
Marshal.FreeHGl obal(bufPtr);
bufPtr = IntPtr.Zero;
}
catch (Exception e)
{
System.Windows. Forms.MessageBo x.Show("Excepti on thrown " + e.Message );
}
}
}
Seems to work okay with a repeat count of < 3. It either explodes or throws
an OutofMemoryExce ption when I repeat the fucntion 3 or more times.
If someone could educate me on whatever i'm doing wrong here, I would muchly
appreciate!
Thanks,
Brandon