[Mono-dev] Embedding Mono + SWIG string return values leads to bad free

Ewen Cheslack-Postava ewencp at cs.stanford.edu
Mon Apr 21 17:36:02 EDT 2008


Hi,

I'm embedding Mono and using SWIG to wrap a few simple C++ objects.
They use PInvoke to wrap these objects and for string/char* return
values they use a C# delegate in order to obtain a string owned by the
GC so it can safely be returned.  They use a simple C# static method
where the string is passed in and immediately returned to do this.  I
assume the magic that's happening there is that the marshalling for
the inputs causes a copy of the string to be created and that same one
is returned.

This seems to work well on Linux and Mac OS X, but on Windows it
causes an exception when the GC tries to free that same memory.  I've
verified that I do in fact get a new copy of the string out at a
different address from the original.  It looks like maybe the string
is just being double freed.  The specific error I get (only in the
Visual Studio debugger) is:

HEAP[x.exe]: Invalid Address specified to RtlFreeHeap( 01E00000, 00166C78 )

and that address is in fact the address of the new string that was
allocated.  I ran under valgrind in linux and it didn't complain about
any double deletes, which is why I assume this is working ok there.

Any ideas on how to resolve this?  I've even tried changing the method
they use to create yet a new copy of the string (and careful not to
just use clone which just returns this) and its still causing the
problem.  I know another option is the method described in the mono
pinvoke docs to return an intptr and then convert in c#, but I was
hoping to avoid major modifications to swig.

Thanks,
Ewen


More information about the Mono-devel-list mailing list