c# - 如何调用 scanf 而不是 Console.ReadLine()?

标签 c# c dll pinvoke dllimport

简单的问题:我应该从控制台读取一些变量,但我不能使用 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/

相关文章:

c# - 用于创建动态Where子句的表达式树抛出与参数相关的错误

c - 将数据广播到 n 个具有不同生命周期的线程

c - C(Linux) 中的 fopen 返回 "Too many open files"

c++ - 手动注册 OCX 文件

c++ - 函数名称修改。 _cdecl约定

c# - Xamarin Forms - 仅在图像而不是整个屏幕上使用捏合手势

c# - Unity汽车自行转向

java - Java 中的 HMAC-SHA256/从 C# 翻译

C : Is this array initialization legal?

c# - 从 C# 调用具有复杂用户定义类型 (UDT) 的 VB6 DLL 函数