4

How can we use callback function in C#?

Cœur
  • 37,241
  • 25
  • 195
  • 267
vishal_niist
  • 99
  • 1
  • 3
  • 10
  • Can you give a more concrete example of what you want? Your question is too generic to answer. – Oded Jun 22 '10 at 10:05
  • Please be more specific. – Darin Dimitrov Jun 22 '10 at 10:05
  • 2
    possible duplicate of [What is a callback?](http://stackoverflow.com/questions/2139812/what-is-a-callback) – Hans Olsson Jun 22 '10 at 10:06
  • Callbacks are used in c++ as a special cases of remote calls that execute as part of a single thread. A callback is issued in the context of a remote call. Any remote procedure defined as part of the same interface as the static callback function can call the callback function.i want to use same cases in c# so i am specifially want to know about this. So i want to use – vishal_niist Jun 22 '10 at 10:15

3 Answers3

4

I think what you are looking for is "delegates". For example:

public MyClass
{
  public delegate void MyCallback(object sender, string MyArg);

  public string DoSomeWork(string Foo, MyCallback mcb)
  {
    mcb(this, Foo);
    return Foo;
  }
}

You can also use delegates to define events. For example, if you wanted an event in MyClass called "OnMyCallback", define it using:

...
public event MyCallback OnMyCallback;
...

Cheers, Adam

AJ.
  • 1,621
  • 1
  • 10
  • 23
2

Reading the questions as: "I want to call a native c++ callback from C#".

You need to create a delegate on the managed/C# side of the boundary.

C++:

DECLARE_CALLBACK(SampleChannelCallback, void, (void* ptr, uint id, void* data));

C#:

[UnmanagedFunctionPointerAttribute(CallingConvention.Cdecl)]
delegate void NativeCallbackDelegate(IntPtr ptr, uint id, IntPtr data);

If you are using SWIG to create your native wrapper, then add the follow to your SwigUtil.h.

#if defined(SWIG)
// Callback declare macro allows for SWIG to automatically construct a macro for a target language for the macros
#define DECLARE_CALLBACK(NAME, RETURNTYPE, PARAMS) typedef void* NAME; %callback_typemap( NAME )
#else
#define DECLARE_CALLBACK(NAME, RETURNTYPE, PARAMS) typedef RETURNTYPE ( NAME ) PARAMS 
#endif

As your question was not very clear, I'm going to leave it there. If you want more information then please ask in the comments.

HTH,

Dennis
  • 20,275
  • 4
  • 64
  • 80
0

Or are you talking about C# .NET event handlers (expanding on the delegates answer)?

Ogre Psalm33
  • 21,366
  • 16
  • 74
  • 92