繁体   English   中英

在C#中使用带有函数指针和委托的PInvoke

[英]Using PInvoke in C# with function pointer and delegate

我是C#的新手。

我有一个像这样的C文件(我用它来制作DLL文件):

extern "C"
{
    typedef int (__stdcall * t_fun)(int);

    __declspec(dllexport) int __stdcall ExecuteC(int n, t_fun f)
    {
        return f(n);
    } 
}

然后我想使用PInvoke在我的C#代码中使用它。

public delegate int f_delegate(int n);

[DllImport("ExecuteC.dll")]
        public static extern int ExecuteC(int n, f_delegate func);

public static int FunCS(int n){ return n; }

static void Main(string[] args)
{
    int x = ExecuteC(13, FunCS);
    System.Console.WriteLine(x.ToString());
}

当我启动程序时,它立即结束。 这里有什么问题?

我没有尝试运行您的程序,但您确定您不仅仅需要

System.Console.ReadLine()

最后致电停止控制台窗口立即消失?

问题中的代码很好。 您可以通过将其粘贴到全新的项目中并发现其运行良好来轻松地进行验证。

我可以看到的唯一合理的解释是:

  1. 该程序可以正常运行,并且在启动后很快结束,因为这是预期的行为。 毕竟,程序只打印一个值并终止。
  2. 实际上,您的代码与问题中显示的代码不同。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM