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

Carlos Alberto Cortez Guevara carlos at unixmexico.org
Sun Feb 1 19:23:44 EST 2004


I didn't know the problem about the function returns, but will take care
of them then (I had seen that IntPtr return in gtk-sharp, but thought it
wasn't neccessary at all ...)

I've seen duncan looked at a test. However, I'm seeing that if you try
to modify a string n-times, it will continue failing. 

If you have a code like:


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

string a = "Message to be printed";
StringBuilder s = new StringBuilder (a.Length);

for (int i = 1;i <= a.Length; i++) {
	strncpy (dest, src, i);
	Console.WriteLine (dest);


It will print ten "M". I've updated my mono modules from cvs, and I'm
still getting this error. Let me know if my tree is wrong ..

Thanks in advance,

El sáb, 31-01-2004 a las 16:27, Jonathan Pryor escribió:
> 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.
/* The definition of myself */
using Cortez;
using GeniusIntelligence;

public class Carlos : Human, IGenius, ILinuxUser {

	static void Main () {



More information about the Mono-devel-list mailing list