[Mono-devel-list] Re: [PATCH] Improper free of return-value string pointers from unmanaged calls

Gonzalo Paniagua Javier gonzalo at ximian.com
Fri Jun 11 03:47:35 EDT 2004


El vie, 11-06-2004 a las 07:32, Steven Brown escribió:
> Marcus wrote:
> 
> > Freeing the string pointers is the appropriate behavior for .NET 
> > compatibility.
> 
> Could you give me a link to some docs that refer to that?  It's 
> empirically untrue as far as I can tell, as I can repeatedly call a 
> method that dynamically allocates the returned string like:
> 
> MEMEAT_API char *foo(void)
> {
> 	static char *str = "Hello there";
> 	static int i = 0;
> 	char *newstr = (char *) malloc(strlen(str) + 1);
> 	strcpy(newstr, str);
> 	printf("%i: %s\n", i++, newstr);
> 	return newstr;
> }
> 
> and if it was supposed to free the pointers, Microsoft's .NET 
> implementation isn't, as the above bloats the process.  The alternative 
> does not:
> 
> MEMEAT_API char *foo(void)
> {
> 	static char *str = "Hello there";
> 	static int i = 0;
> 	//char *newstr = (char *) malloc(strlen(str) + 1);
> 	//strcpy(newstr, str);
> 	printf("%i: %s\n", i++, str);
> 	return str;
> }
> 
> It doesn't make sense to free such a string pointer, as often string 
> pointers will be coming from .rodata and such.
> 

you have to do:
-----------------------
using System.Runtime.InteropServices;
public class Test {

  [DllImport("foo.so")]
  public static extern IntPtr foo();

  public static void Main() {
    System.Console.WriteLine(Marshal.PtrToStringAuto (foo()));
  }
}
----------------------

when you don't own the string returned.

-Gonzalo





More information about the Mono-devel-list mailing list