1

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

3
  • Add a exception handler to your code. There is an exception occurring in the ExecuteC() method that is terminating the program. Since you don't have an exception handler in main() the default exception handler that the Net Library adds to your project before main is called is handling the exception and exiting. When an exception occurs in the managed code the compiler inserts code that searches up the execution stack and looks for first exception handler. When no exception handler is found in a method the code often skips up to parent method bypassing in your case the WriteLine() function. Commented Apr 23, 2016 at 14:52
  • 1
    Is the title the opposite of what is intended? I think you are trying to call a C method from C#. Commented Apr 23, 2016 at 15:10
  • @MathuSumMut Well, it's complicated. I'm trying to call C function which calls C# method :P Commented Apr 23, 2016 at 16:15

1 Answer 1

3

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.
Sign up to request clarification or add additional context in comments.

1 Comment

Yeah, I specified Cdecl on delegate and on DllImport and it works now, thanks! :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.