c# - Can using UnmanagedMemory.LPTStr instead of .ByValTStr result in memory corruption? Why? -
we have tree view in windows forms app shows files using appropriate file icon using following code. problem call geticon() appears corrupt memory start getting various program crashes can't catch debugger after call.
program work when change managedtype.lptstr managedtype.byvaltstr. true fix or masking problem?
this code appeared working in our last product release , can't see has changed. using .net 4.0. see issue in release mode.
[dllimport("shell32.dll")] private static extern int shgetfileinfo(string pszpath, uint dwfileattributes, out shfileinfo psfi, uint cbfileinfo, shgfi uflags); [structlayout(layoutkind.sequential)] private struct shfileinfo { public shfileinfo(bool b) { hicon=intptr.zero; iicon=0; dwattributes=0; szdisplayname = ""; sztypename = ""; } public intptr hicon; public int iicon; public uint dwattributes; [marshalas(unmanagedtype.lptstr, sizeconst = 260)]//works if .byvaltstr used instead public string szdisplayname; [marshalas(unmanagedtype.lptstr, sizeconst = 80)]//works if .byvaltstr used instead public string sztypename; }; public static icon geticon(string strpath, bool bsmall) { shfileinfo info = new shfileinfo(true); int cbfileinfo = marshal.sizeof(info); shgfi flags; if (bsmall) flags = shgfi.icon|shgfi.smallicon|shgfi.usefileattributes; else flags = shgfi.icon|shgfi.largeicon|shgfi.usefileattributes; shgetfileinfo(strpath, 256, out info,(uint)cbfileinfo, flags); return icon.fromhandle(info.hicon); }
well, it's not proper lpstr in struct, can't try marshal 1 , expect work:
typedef struct _shfileinfo { hicon hicon; int iicon; dword dwattributes; tchar szdisplayname[max_path]; tchar sztypename[80]; } shfileinfo; lptstruse when you've allocated special block of memory hold string (usually inmarshal.allochglobalor similar), you've copied onstringunmanaged memory area.byvaltstruse when literally passing in actual string value, not reference area in memory.
the struct wants proper value, not pointer.
Comments
Post a Comment