【问题标题】:Calling C# method in C code在 C 代码中调用 C# 方法
【发布时间】:2016-08-17 03:59:28
【问题描述】:

这就是我的 C 代码:

__declspec(dllexport) int ExecuteC(int number, int (*f)(int)) {
    return f(number);
}

它被编译成'Zad3DLL.dll'文件。

这是我的 C# 代码:

class Program
{
    static int IsPrimeCs(int n)
    {
        for(int i = 2; i < n; i++)
        {
            if (n % i == 0) return 0;
        }
        return 1;
    }

    [UnmanagedFunctionPointer(CallingConvention.StdCall)]
    public delegate int FDelegate(int n);

    [DllImport("Zad3DLL.dll", EntryPoint = "ExecuteC")]
    static extern int ExecuteC(int n, FDelegate fd);

    static void Main(string[] args)
    {
        string s;
        FDelegate fd = new FDelegate(IsPrimeCs);
        while ((s = Console.ReadLine()) != null)
        {
            int i = Int32.Parse(s);
            int res = ExecuteC(i, fd);
            Console.WriteLine(res == 0 ? "Nie" : "Tak");
        }
    }
}

问题是当 c# 程序执行到调用 ExecuteC 函数时,它只是完成执行而没有任何错误。我只是在 Visual Studio 的输出窗口中得到zad3.vshost.exe' has exited with code 1073741855。我做错了什么?

顺便说一句,不要告诉我我可以更有效地搜索素数,这只是示例代码:P

【问题讨论】:

  • 向您的代码添加异常处理程序。在终止程序的 ExecuteC() 方法中发生异常。由于您在 main() 中没有异常处理程序,因此 Net 库在调用 main 之前添加到您的项目中的默认异常处理程序正在处理异常并退出。当托管代码中发生异常时,编译器会插入代码,搜索执行堆栈并查找第一个异常处理程序。当在方法中找不到异常处理程序时,代码通常会跳过在您的情况下绕过 WriteLine() 函数的父方法。
  • 标题是否与预期相反?我认为您正在尝试从 C# 调用 C 方法。
  • @MathuSumMut 嗯,这很复杂。我正在尝试调用调用 C# 方法的 C 函数:P

标签: c# .net c visual-studio


【解决方案1】:

我有两个选择:

  1. 检查两个项目的 x86 或 x64 构建设置。
  2. 验证调用约定。我认为在 VC++ 中默认为cdecl,因此请尝试在DllImport 属性以及委托声明中指定。

【讨论】:

  • 是的,我在委托和 DllImport 上指定了 Cdecl,现在它可以工作了,谢谢! :)
猜你喜欢
  • 2013-01-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多