[Mono-dev] PtrToStructure, FreeHGlobal, then access to the structure

Robert Jordan robertj at gmx.net
Tue Aug 12 05:33:36 EDT 2008

Andy Hume wrote:
> In the class library I see a few pieces of code like the following.  Am I
> correct in thinking that code like this is bad?

Only if the .Name ptr is pointing to a memory block inside the
struct's area. So it depends on the specification of the
struct being marshaled.

>    info = Marshal.PtrToStructure (ptr, ...);
>    Marshal.FreeHGlobal (ptr);
>    // now we access the structure 
>    int id = info.Id;
>    string name = Marshal.PtrToStringUni (info.Name);
> Since the structure might contain only blittable types then the structure
> reference may simply be to the native memory and not to a managed copy?  So
> accessing a field there is accessing free'd memory...

IntPtrs are blittable.


More information about the Mono-devel-list mailing list