在C代码中调用C#方法

时间:2016-04-23 14:35:23

标签: c# .net c visual-studio

所以有我的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。我做错了什么?

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

1 个答案:

答案 0 :(得分:1)

我有两个选择:

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