Octothorp
Octothorp

Reputation: 135

Calling C# method in C code

So there is my C code:

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

It is compiled to 'Zad3DLL.dll' file.

There's my C# code:

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");
        }
    }
}

The problem is when execution of c# program comes to the point when it is calling ExecuteC function it just finishes execution without any error. I just get zad3.vshost.exe' has exited with code 1073741855 in Output window in Visual Studio. What am I doing wrong?

BTW Don't tell me I can search for prime numbers more efficently, it is just example code :P

Upvotes: 1

Views: 541

Answers (1)

Darko Djuric
Darko Djuric

Reputation: 754

I have two options in mind:

  1. Check your build settings x86 or x64 for both projects.
  2. Verify calling convention. I think that in VC++ default is cdecl, so try to specify in DllImport attribute as well as on the delegate declaration.

Upvotes: 3

Related Questions