Here is my code:
internal void Show() { if (Parent == null) throw new NullReferenceException(); EDITBALLOONTIP ebt = new EDITBALLOONTIP(); ebt.cbStruct = Marshal.SizeOf(ebt); ebt.pszText = Text; ebt.pszTitle = Caption; ebt.ttiIcon = (int)Icon; IntPtr ptrStruct = Marshal.AllocHGlobal(Marshal.SizeOf(ebt)); Marshal.StructureToPtr(ebt, ptrStruct, true);
And here is the structure:
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] private struct EDITBALLOONTIP { internal int cbStruct; internal string pszTitle; internal string pszText; internal int ttiIcon; }
Why does this work fine in Windows XP and .NET 3.5 and throw exceptions in Windows 7 and .NET 4.0? Maybe this is a CharSet problem?
====================== solvable ======================= =
Solution and explanation
As you can see Marshal.StructureToPtr (ebt, ptrStruct, true ); has a third parameter equal to true. This means that the system will try to free the last allocated memory for ptrStruct. But when the Show() method is called for the first time, there was no allocated memory for this structure (ptrStruct = IntPtr.Zero). Therefore, the system will try to free memory located with a null pointer. And of course, this will throw an exception. Windows XP ignores this, but Windows 7 does not.
And here is the best IMHO solution:
Marshal.StructureToPtr(ebt, ptrStruct, false);
source share