scanf or sscanf

B

Barry Kelly

ewolfman said:

Which bit couldn't you get to work? This works for me:

---8<---
using System;
using System.Runtime.InteropServices;

class Program
{
[DllImport("crtdll.dll",
CallingConvention=CallingConvention.Cdecl,
CharSet=CharSet.Unicode,
ExactSpelling=true)]
static extern int swscanf(string buffer, string format,
out int value);

static void Main()
{
int value;
swscanf("42", "%d", out value);
Console.WriteLine(value);
}
}
--->8---

I note that scanf and related functions are not typesafe and it would be
easy to accidentally create buffer overrun problems when scanning
strings etc.
In short, how can I call scanf or sscanf directly from C# (i.e. I'd
rather have a DllImport and perform the call directly as I would in
C++, instead of using custom classes).

The scanf function style relies heavily on passing untyped pointers,
where the type information is in the string buffer, disassociated from
the actual pointers passed.

In the interests of security and reliability, I suggest that you
consider using Regex or some other safer option instead.

-- Barry
 
E

ewolfman

The scanf method call for example, does not read any input from the
user. The debugger reaches the scanf code line, and simply skips it
without pausing and waiting for the user to enter data.

So I'm using sscanf instead. This seems to work, but since .NET works
with explicit typing, I guess that there is no way I can pass multiple
parameter references (which causes me to write multiple overloads for
sscanf external declaration).

For example:
[DllImport("msvcrt.dll", CharSet = CharSet.Ansi,
CallingConvention = CallingConvention.Cdecl)]
public static extern int sscanf(string buffer, string format,
ref int myVar, ref int myVar2);

[DllImport("msvcrt.dll", CharSet = CharSet.Ansi,
CallingConvention = CallingConvention.Cdecl)]
public static extern int sscanf(string buffer, string format,
ref int myVar, ref int myVar2, StringBuilder myVar3);
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top