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

Andy Hume andyhume32 at yahoo.co.uk
Tue Aug 19 10:33:56 EDT 2008

Thanks Robert.  Makes sense in hindsight, that the managed struct is a copy
of the native source (the native struct being copied onto the managed
struct's memory IIUC)!  Thus one bug report only (#417256 in Win32


Robert Jordan wrote:
> 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.
> Robert
> _______________________________________________
> Mono-devel-list mailing list
> Mono-devel-list at lists.ximian.com
> http://lists.ximian.com/mailman/listinfo/mono-devel-list

View this message in context: http://www.nabble.com/PtrToStructure%2C-FreeHGlobal%2C-then-access-to-the-structure-tp18940257p19050896.html
Sent from the Mono - Dev mailing list archive at Nabble.com.

More information about the Mono-devel-list mailing list