[Mono-devel-list] Problem with P/Invoke

Jonathan Pryor jonpryor at vt.edu
Sat Jan 31 17:27:24 EST 2004


There are a couple of problems with your DllImport statement.  First of
all, strncpy(3) is documented as taking a "size_t n" argument, so your
third argument should be uint, not int, though this really won't matter
unless you try passing in negative values.

The second problem is more serious: you have a "string" return type. 
.NET (and Mono), when marshaling functions with class return types (not
structures), will attempt to free the memory of the of the returned
object.  It is assumed that the runtime is supposed to take ownership of
the memory in the return value.

Since strncpy(3) returns it's first argument, you *really* don't want
the runtime to be freeing this memory, so you have two alternatives: use
a "void" return type, or use System.IntPtr (which can then be converted
to a string -- without freeing the memory -- using
System.Runtime.InteropServices.Marshal.PtrToStringAnsi).

Thus, your DllImport should be:

	[DllImport ("libc.so")]
	private static extern IntPtr strncpy (StringBuilder dest,
		string src, uint len);

Now, the bad news begins.  When I try this under Mono 0.29, the code
doesn't work correctly.  Nothing appears to be copied.

Could someone running CVS try this example, with the above DllImport
statement (and appropriate casts to uint), and see if this works?

Thanks,
 - Jon


On Fri, 2004-01-30 at 14:16, Carlos Alberto Cortez Guevara wrote:
> Hi,
> 
> I was playing with some P/Invoke samples, and I found that the next code
> doesn't work perfect.
> 
> I'm loading the strncpy function from the standard library (libc), and
> the first call works perfect. However, in the second call (and third,
> ..) it doesn't work.
> 
> Is this a bug?
> 
> Regards,
> Carlos.




More information about the Mono-devel-list mailing list