Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

scanf() and DllImport

72 views
Skip to first unread message

Chris

unread,
Mar 27, 2004, 9:11:33 AM3/27/04
to
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


Nicholas Paldino [.NET/C# MVP]

unread,
Mar 27, 2004, 9:16:17 AM3/27/04
to
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]
- m...@spam.guard.caspershouse.com

"Chris" <chris...@pandora.be> wrote in message
news:pYf9c.51801$js3.3...@phobos.telenet-ops.be...

Chris

unread,
Mar 27, 2004, 10:08:36 AM3/27/04
to
thanks a lot !

Chris

"Nicholas Paldino [.NET/C# MVP]" <m...@spam.guard.caspershouse.com> wrote in
message news:OxJCTYAF...@tk2msftngp13.phx.gbl...

0 new messages