简单的问题:我应该从控制台读取一些变量,但我不能使用 Console 类。所以我正在写这样的东西
using System;
using System.Runtime.InteropServices;
namespace ConsoleApplication153
{
class Program
{
static unsafe void Main()
{
printf("%s" + Environment.NewLine, "Input a number");
int* ptr;
scanf("%i", out ptr);
printf("%i", (*ptr).ToString());
}
[DllImport("msvcrt.dll", CallingConvention = CallingConvention.Cdecl)]
private static extern void printf(string format, string s);
[DllImport("msvcrt.dll", CallingConvention = CallingConvention.Cdecl)]
private static unsafe extern void scanf(string format, out int* ptr);
}
}
但它失败并出现 NullReferenceException。请帮忙,我该怎么办? Printf 有效,但 scanf - 无效。 TNx
好的。完整的任务听起来像这样:“如何从用户获取变量并在 C# 中打印它的值而不使用 Console 类”。
最佳答案
对于%i
,您需要传递一个指向整数的指针。您正在传递一个指向未初始化的整数指针的指针。不好。
像这样声明函数:
[DllImport("msvcrt.dll", CallingConvention = CallingConvention.Cdecl)]
private static extern void scanf(string format, out int value);
将 int 作为 out
参数传递是通过将指针传递给 int
来实现的。
这样调用它:
scanf("%i", out value);
这里不需要不安全的代码。
如果您要传递字符串,您还需要将 %s
传递给 printf
,就像您在第二次调用 printf< 时所做的那样
。
关于c# - 如何调用 scanf 而不是 Console.ReadLine()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18803539/