The following example code from a console application shows how to use pass a C# function to be used as a callback to an unmanaged C++ function called using P/Invoke -
C# Callback -
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
delegate uint CSCALLBACK([MarshalAs(UnmanagedType.IUnknown)] object document, IntPtr context, double progress);
[DllImport("ArrayMarshal.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Unicode)]
static extern int Longtime_function([MarshalAs(UnmanagedType.IUnknown)] object document, CSCALLBACK cbFunc, IntPtr context);
The C# Callback function -
static uint MyCallback(object document, IntPtr context, double progress)
{
//Your code here
}
Call the C++ function (example allocates unmanaged memory for the context pointer and stores an int value) -
IntPtr ptContext = Marshal.AllocHGlobal(sizeof(int));
Marshal.WriteInt32(ptContext, 42);
int iret = Longtime_function(aObjects[0], MyCallback, ptContext);