all groups > dotnet interop > july 2003 >
You're in the

dotnet interop

group:

Freeing memory immediately after Marshal.PtrToStruct()


Freeing memory immediately after Marshal.PtrToStruct() Michel Gallant
7/6/2003 10:58:33 AM
dotnet interop:
Marshal.PtrToStructure() documentation indicates that it returns
a "newly allocated managed object" from unmanaged memory described by IntPtr.
Can the allocated memory be free'd immediately after PtrToStructure() ??
and are all members of the managed structure returned accessible?
Are there cases where members must be explicitly copied (Marshal.Copy())
*before* freeing memory??

e.g. -------------
pProvInfo = Marshal.AllocHGlobal((int)cbSize);
WinCapi.CertGetSomething(......, pProvInfo, ref cbSize)
MyStruct ckinfo = (MyStruct)Marshal.PtrToStructure(pProvInfo, typeof(MyStruct));
Marshal.FreeHGlobal(pProvInfo);
Console.WriteLine("ContainerName: {0}", ckinfo.ContainerName) ;
-----------------

Thanks,
- Mitch Gallant

Re: Freeing memory immediately after Marshal.PtrToStruct() Mattias Sjögren
7/10/2003 12:51:25 AM
Hi Michel,

[quoted text, click to view]

Yes, PtrToStructure performs a deep copy.


[quoted text, click to view]

Only if the struct contains a pointer (IntPtr perhaps) to another
place in the unmanaged memory, so that the pointer would be invalid if
the memory was freed first.



Mattias

--
Mattias Sjögren [MVP] mattias @ mvps.org
http://www.msjogren.net/dotnet/
AddThis Social Bookmark Button