我有这样一段代码(从诺基亚PC连接3.2示例代码,在C#):运行“GC.Collect的”修复我的崩溃,但我不明白为什么
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);
如果我在开始时运行GC.Collect()
,然后我没有收到AccessViolationException
。但除非必要,否则我不想减慢此功能。我试过把GC.Keepalive
放在不同的地方,但没有成功。
CA_FOLDER_INFO
被定义为:
[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;
}
我不这样做,在这种情况下,都要求使用字符串,并改变它们的定义,以IntPtr
似乎使异常消失。
这是怎么回事,防止异常的正确方法是什么?
不要忘记在一个try-finally包装中,当你完成bufItem时调用Marshal.FreeHGlobal。 – sisve 2009-06-15 10:32:36