Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store a function pointer in C#

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?

like image 338
y2k Avatar asked Mar 31 '10 03:03

y2k


People also ask

How do you store function pointers?

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.

Where do we use function pointers in C?

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.

Where are function pointers stored in memory?

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.


3 Answers

.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.

like image 185
John Saunders Avatar answered Oct 17 '22 04:10

John Saunders


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();
like image 29
Dave Swersky Avatar answered Oct 17 '22 05:10

Dave Swersky


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.

like image 8
Ben Voigt Avatar answered Oct 17 '22 06:10

Ben Voigt