Search code examples
c#cdelegatespinvokefunction-pointers

Using PInvoke in C# with function pointer and delegate


i'm new in C#.

I have a C file like this (and im using it to make DLL file) :

extern "C"
{
    typedef int (__stdcall * t_fun)(int);

    __declspec(dllexport) int __stdcall ExecuteC(int n, t_fun f)
    {
        return f(n);
    } 
}

Then i want to use it in my C# code using PInvoke.

public delegate int f_delegate(int n);

[DllImport("ExecuteC.dll")]
        public static extern int ExecuteC(int n, f_delegate func);

public static int FunCS(int n){ return n; }

static void Main(string[] args)
{
    int x = ExecuteC(13, FunCS);
    System.Console.WriteLine(x.ToString());
}

And when i start my program it ends immediatly. What is the problem here?


Solution

  • The code in the question is fine. You can easily verify this by pasting it into brand new projects and discovering that it works perfectly well.

    The only plausible explanations that I can see are:

    1. The program runs correctly and ends very soon after it starts because that is the expected behaviour. After all the program simply prints a single value and terminates.
    2. Your code is in fact different from that presented in the question.