1

I'm coding a server and I've set up a TCP connection with all the clients. Now, when a Client sends a packet I check the opcode of the packet so I can process it.

At the moment, I have an OpcodeHandler struct that currently contains String name but I also want it to have a C++-typed function pointer that calls another function, so that when I create an array with the struct as type and I initialize the array like this:

opcodes = new OpcodeHandler[max_opcodes] 
{
  new OpcodeHandler("someopcodenamehere", Somefunctionname);
  // more new's..
}

That the function named in the second argument of the constructor : 'Somefunctionname' gets called when calling the function pointer. I've heard that this is possible with delegates since they behave just like function pointers in C++, but all of my tries were useless.

2
  • And what would be the signature of the function? Commented Aug 2, 2013 at 12:10
  • a void return type, with one argument : (Packet data) Commented Aug 2, 2013 at 12:11

2 Answers 2

1

You said you have a struct OpcodeHandler that you want to create an array of.

Now I don't know what else the OpcodeHandler does, but I'll suggest something simpler:

Dictionary<string, Action<PacketData>> OpcodeHandlers = new Dictionary<string, Action<PacketData>>();

This is a dictionary of delegates.

You can add functions to it like so:

OpcodeHandlers["someopcodenamehere"] = Somefunctionname;

and call the functions like so:

OpcodeHandlers["someopcodenamehere"](packetData);


Edit:
You can also fill the Dictionary like this:

Dictionary<string, Action<PacketData>> OpcodeHandlers = new Dictionary<string, Action<PacketData>>
{
  { "functionName1", function1 },
  { "functionName2", function2 }
};
0
1
new OpcodeHandler("someopcodenamehere", packetData => 
        Somefunctionname(packetData))

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.