Let's say I want to store a group of function pointers in a List<(*func)>
, and then later call them, perhaps even with parameters... Like if I stored in a Dict<(*func), object[] params>
could I call the func with the parameters? How would I do this?
Function pointers can be stored in variables, structs, unions, and arrays and passed to and from functions just like any other pointer type. They can also be called: a variable of type function pointer can be used in place of a function name.
In C, we can use function pointers to avoid code redundancy. For example a simple qsort() function can be used to sort arrays in ascending order or descending or by any other order in case of array of structures. Not only this, with function pointers and void pointers, it is possible to use qsort for any data type.
That depends on your compiler and target environment, but most likely it points to ROM—executable code is almost always placed in read-only memory when available.
.NET uses delegates instead of function pointers. You can store a delegate instance like any other kind of object, in a dictionary or otherwise.
See Delegates from the C# Programming Guide on MSDN.
You can absolutely have a dictionary of functions:
Dictionary<string, Action<T>> actionList = new Dictionary<string, Action<T>>();
Dictionary<string, Func<string>> functionList = new Dictionary<string, Func<string>>();
actionList.Add("firstFunction", ()=>{/*do something;*/});
functionList.Add("firstFunction", ()=>{return "it's a string!";});
You can then call the methods like this:
string s = functionList["firstFunction"].Invoke();
Look at the C# documentation on delegates, which is the C# equivalent of a function pointer (it may be a plain function pointer or be curried once to supply the this parameter). There is a lot of information that will be useful to you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With