Reputation: 61
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.
Upvotes: 1
Views: 775
Reputation: 881
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 }
};
Upvotes: 1
Reputation: 3082
new OpcodeHandler("someopcodenamehere", packetData =>
Somefunctionname(packetData))
Upvotes: 1