【问题标题】:Using PInvoke in C# with function pointer and delegate在 C# 中使用带有函数指针和委托的 PInvoke
【发布时间】:2014-05-28 09:16:48
【问题描述】:

我是 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());
}

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

【问题讨论】:

  • 您需要进行一些诊断。立即结束是不好的。

标签: c# c delegates pinvoke function-pointers


【解决方案1】:

我没有尝试运行你的程序,但你确定你不只是需要一个

System.Console.ReadLine()

最后调用以停止控制台窗口立即消失?

【讨论】:

  • 不,我的程序在调用 ExecuteC 函数时结束。
  • 在这种情况下,我建议您在 Main 函数周围添加一个 try{ ... } catch (Exception ex) { ... } 以获得有关异常的更多信息。但是,如果错误在非托管代码中,则必须单独调试该问题。
【解决方案2】:

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

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

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

【讨论】:

  • 嗯,这很奇怪。也许问题是,我有 2 个不同解决方案的项目。我创建了新的解决方案并在那里制作了 2 个项目,一切正常(使用与上面相同的代码)。谢谢你的帮助:)
猜你喜欢
  • 1970-01-01
  • 2012-12-29
  • 1970-01-01
  • 2016-10-17
  • 1970-01-01
  • 1970-01-01
  • 2010-09-28
  • 2013-10-18
  • 2011-12-27
相关资源
最近更新 更多