scanf() and DllImport

  • Thread starter Thread starter Chris
  • Start date Start date
C

Chris

Hi,

using DLLImport as follows :

[DllImport("msvcrt.dll", CharSet=CharSet.Ansi,
CallingConvention=CallingConvention.Cdecl)]
public static extern int scanf(string format, ref int s1);

then using :
int sum=0;
scanf("%d", ref sum);
Console.WriteLine("Using int = {0}", sum);

OK, this works
Now using a string ...

[DllImport("msvcrt.dll", CharSet=CharSet.Ansi,
CallingConvention=CallingConvention.Cdecl)]
public static extern int scanf(string format, ref string s1);

string strSum=" ";
scanf("%s", ref strSum);
==> NullReferenceException

Omitting 'ref' doesn't throw an exception but doesn't give me anything back
in 'strSum' of course.

Any ideas ?

Second question :
isn't there any way to import printf() using only 1 DllImport declaration
such as for example :
[DllImport("msvcrt.dll", CharSet=CharSet.Ansi,
CallingConvention=CallingConvention.Cdecl)]
public static extern int printf(string format, params object[] s2);

Unfortunately it does not work properly :-((

thnx
Chris
 
Chris,

You should use the StringBuilder class instead. This is the way that
you pass strings where the content of the string could be modified. Also,
do not pass it by ref, just pass it normally (and make sure you use the
MarshalAs attribute to indicate that you are marshaling an ANSI string).

Hope this helps.
 
thanks a lot !

Chris

Nicholas Paldino said:
Chris,

You should use the StringBuilder class instead. This is the way that
you pass strings where the content of the string could be modified. Also,
do not pass it by ref, just pass it normally (and make sure you use the
MarshalAs attribute to indicate that you are marshaling an ANSI string).

Hope this helps.


--
- Nicholas Paldino [.NET/C# MVP]
- (e-mail address removed)

Chris said:
Hi,

using DLLImport as follows :

[DllImport("msvcrt.dll", CharSet=CharSet.Ansi,
CallingConvention=CallingConvention.Cdecl)]
public static extern int scanf(string format, ref int s1);

then using :
int sum=0;
scanf("%d", ref sum);
Console.WriteLine("Using int = {0}", sum);

OK, this works
Now using a string ...

[DllImport("msvcrt.dll", CharSet=CharSet.Ansi,
CallingConvention=CallingConvention.Cdecl)]
public static extern int scanf(string format, ref string s1);

string strSum=" ";
scanf("%s", ref strSum);
==> NullReferenceException

Omitting 'ref' doesn't throw an exception but doesn't give me anything back
in 'strSum' of course.

Any ideas ?

Second question :
isn't there any way to import printf() using only 1 DllImport declaration
such as for example :
[DllImport("msvcrt.dll", CharSet=CharSet.Ansi,
CallingConvention=CallingConvention.Cdecl)]
public static extern int printf(string format, params object[] s2);

Unfortunately it does not work properly :-((

thnx
Chris
 
Back
Top