I have this piece of code (from the nokia pc connectivity 3.2 example code, in C#)
DAContentAccessDefinitions.CA_FOLDER_INFO folderInfo =
new DAContentAccessDefinitions.CA_FOLDER_INFO();
folderInfo.iSize = Marshal.SizeOf(folderInfo); //(32)
IntPtr bufItem = Marshal.AllocHGlobal(folderInfo.iSize);
//I often get a AccessViolationException on the following line
Marshal.StructureToPtr(folderInfo, bufItem, true);
If I run GC.Collect() at the start of this, then I don't get an AccessViolationException. But I don't want to slow down this function unless necessary. I've tried putting GC.Keepalive in various places, but without success.
CA_FOLDER_INFO is defined as:
[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
public struct CA_FOLDER_INFO
{
public int iSize;
public int iFolderId;
public int iOptions;
public string pstrName;
public string pstrPath;
public int iSubFolderCount;
public IntPtr pSubFolders;
public IntPtr pParent;
}
I don't, in this instance, require either of the strings, and changing their definitions to IntPtr seems to make the exception go away.
What is going on here, and what is the correct way to prevent the exception?