views:

49

answers:

1

The Following is code of a function from a unmanged dll. It takes in a function pointer as argument and simply returns value returned by the called function.

extern __declspec(dllexport) int  _stdcall callDelegate(int (*pt2Func)());
extern __declspec(dllexport) int  _stdcall callDelegate(int (*pt2Func)())
{
    int r = pt2Func();
    return r;
}

In managed C# code I call the umanged function above with a delegate.

  unsafe public delegate int mydelegate( );

    unsafe public int delFunc()
    {
             return 12;
    }

    mydelegate d = new mydelegate(delFunc);
    int re = callDelegate(d);
   [DllImport("cmxConnect.dll")]
    private unsafe static extern int callDelegate([MarshalAs(UnmanagedType.FunctionPtr)] mydelegate d);

This all works great !! but if I want my function pointer/delegate to take arguments it crashed the program. So if I modify the code as follows my program crashes.

Modified unmanaged c++ -

extern __declspec(dllexport) int  _stdcall callDelegate(int (*pt2Func)(int));
extern __declspec(dllexport) int  _stdcall callDelegate(int (*pt2Func)(int))
{
    int r = pt2Func(7);
    return r;
}

Modified C# code -

unsafe public delegate int mydelegate( int t);

        unsafe public int delFunc(int t)
        {
                 return 12;
        }

        mydelegate d = new mydelegate(delFunc);
        int re = callDelegate(d);
+1  A: 

The calling convention for the function pointer is wrong. Make it look like this:

 int (__stdcall * pt2Func)(args...)
Hans Passant