How to save state and return to deep function C?

Background

I am porting an existing C program to work in an online game using Emscripten.

The problem is that Emscripten wants the program to be organized around one function called 60 times per second. This is normal for the main game cycle, except that there are quite a few places where the code displays a set of parameters, and then waits for a key to be pressed to select an option. This is expressed as a function deep in the call hierarchy, using getch () to wait for a key to be pressed. I find it difficult to figure out how to set this to the required Emscripten style for a function that starts and then ends.

Question

When the code called the function that called the function that called the function, is there an easy way to save the entire state of the call so that I can return to the same place later?

What i tried

  • The approach I'm using now is to set a global state variable to indicate my current location and write all the things on the stack that seem important to static variables. Then I come back from all the functions. For re-entry, I use a global variable to decide which function to call and which variables to reload from the stored data. However, this involves writing a lot of additional code and is very error prone.

  • I was wondering about using a stream for game logic and just sending messages from a GUI stream, but the current stream API inside Emscripten seems to require me to try to copy all the game data into a message so that it looks a lot bigger in order to get little benefit.

  • Emscripten supports setjmp / longjmp, but as I understand it, this only does half the work. I think I can use longjmp to just go back from the deep function to the top level, but I don’t see anyway that I can use it to go back to where I was later.

Any best ideas on how I can do this?

+7
c emscripten
source share
1 answer

You cannot return from callstack and re-enter it again. You can only make deeper calls to still be able to return to your current state. As soon as the function returns, the same stack (the same physical memory location) will be reused for the next calls, and the values ​​will be overwritten.

I do not know Emscripten; can getch () shell recursively control a loop before a key is pressed?

setjmp / longjmp keeps the stack offset, but not the value on the stack. This is only useful for outputting multiple frames from the stack; this closest C comes to the exception thrown.

+1
source share

All Articles