【发布时间】: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