0

In C or C++ it is possible to use a function pointer as a parameter to another function like this:

int example(FUNPTR a)
{
  /* call the function inside */
  a();
}

And I also know that we can use delegates in c# as function pointer, but what if the method I want to assign to the delegate exists in another class, does that mean both class need to have a same delegate declaration?

For example:

class a
{
   public delegate void processData(Byte[] data);

   public void receivData(ProcessData dataHandler)
   {
      NetworkStream stream;
      Byte[] data_buffer = new Byte[100];

      /* receive data from socket interface */

      stream.Read(data_buffer, 0, data_buffer.Length);

      dataHandler(data);
   }
}

Also, I want to use this receivData function in class b like this:

class b
{

   public delegate void processData(Byte[] data);

   class a = new a();

   a.receivData(new processData(b.dataHandler));

   public void dataHandler(Byte[] array)
   {
      /* handling of the array*/
   }
}

Please let me know if the declaration of processData in class b is necessary.

Is this the right way to pass a function pointer in C#?

2 Answers 2

3

You do not need multiple declarations of the delegate type, and in fact this will cause problems in your example.

a.receiveData is expecting a delegate of type a.processData. But when you new up a processData delegate in b, that will find the b.processData type -- which is a different type (even though it has the same signature).

So you should remove the delegate type declaration from b, and change your call to:

a.receivData(new a.processData(b.dataHandler));

But in fact the explicit new is unnecessary: since b.dataHandler has the correct signature, the C# compiler will insert an implicit conversion to a.processData, so you can write:

a.receivData(b.dataHandler);
Sign up to request clarification or add additional context in comments.

Comments

1

Yep, the method should have the same signature

1 Comment

Thanks for the reply. Is there a better way of doing this. Having to declare the a same delegates in different classes sounds redundant.

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.