I tried to find some kind of things that allow to "save functions" such as: Once running the program (included some functions) and we will save functions's address in memory after that, we can re-use these functions without execution any more. Could you give me some ideas (in general or particular in Python, C/C++,...). I have googled this but I didn't get it :(. I was thinking of some kind of memory management (allocation, freedom of memory, resident memory...I guess) For example: I have a function with its address "at " (that is generated when program runs) How can I reuse them?! Thanks in advance
1 Answer
Well, in Python, functions are objects, so you can pass them around, assign them, and call them from any label you've used to alias them. You can also get the id (memory location/guid equivalent). If what you mean is memoization/lazy loading of data, there are a number of resources available on SO and through Google for doing that sort of thing. They generally look like:
class Foo(object):
@staticmethod
def get_val():
try:
return Foo.__val
except AttributeError:
#do run-once logic here, assign to Foo.__val
return Foo.__val
5 Comments
s0nl4c
I mean, for example, first time (only one time), we run a F function somewhere. Now, in memory, the F function is stored as <function f_new at 0x000000000388FE48>. What I mean is that we can call F (by address or something) without re-execution. Normally, its easy to call F if the program is running, but what I need is that we can call F even that program is stopped. Sometimes, that is very useful for the linearisation of a recursive algorithm. We can "save functions" once running them and re-use them after. Btw, many thanks for answering!
Silas Ray
@azalea When you say, "...[the] function is stored as..." do you mean the result (return value) of the function or the actual function itself? I'm assuming the former, since you talk about not re-executing the code again. An alternative method to the try/except block would be to actually overwrite the value stored to the label you use to access the function when it is returned. Is this what you are looking to do?
s0nl4c
No, I mean that the function is resident in memory as the address 0x....and I am looking for a way that can take a function in memory, we can access and manipulate them (by address) until that we free them from computer memory (i.e. memory-resident virus...I guess). I don't know if you understand or not, the idea is there!
s0nl4c
I mean we can use this function by calling them from memory as well as we call it at first time and then we can do what this functions can do.
Silas Ray
Well, since a function is an object in Python, it is in memory till all the references to it are removed and then it is garbage collected. So when you call it by name, you are calling it in memory.