zsaleeba / picoc

A very small C interpreter
1.45k stars 183 forks source link

How can I call PicoC to run a program in a string calling main() ? #29

Open cesss opened 7 years ago

cesss commented 7 years ago

Reading the source, I saw how to run a program whose source is defined in a file, and do it by either calling main() or not calling it (as a script). This is in picoc.c

Also in picoc.c, I found how to run a program stored in a string rather than in a file, in what's called "surveyor host" mode, but it does it without calling main().

I want both things: Running a program which is already stored in a string, and start its execution at main().

My guess is the following code snippet, but is this correct? I'm afraid the program would be run twice (first time when calling PicocParse() and second time when calling PicocCallMain()) by doing it this way, but I don't know how to achieve it in other way. Didn't find any docs explaining it.

Is the following guess correct? How should I do it?

int picocrun(const char *src, int argc, char **argv) 
    {
    Picoc pc;
    int StackSize = 128*1024; /* space for the stack */

    PicocInitialise(&pc, StackSize);

    if (PicocPlatformSetExitPoint(&pc))
        {
        PicocCleanup(&pc);
        return pc.PicocExitValue;
        }

        PicocParse(&pc, "nofile", src, strlen(src), TRUE, FALSE, TRUE, TRUE);
    PicocCallMain(&pc, argc, argv);
    PicocCleanup(&pc);
    return pc.PicocExitValue;
    }
zsaleeba commented 7 years ago

That looks correct offhand. Give it a try!

cesss commented 7 years ago

Yes, it works fine!!

But I don't understand why, because PicocParse() has a "run now" argument, which is supposed to run the program, and PicocCallMain() also runs the program, so why doesn't it run twice?

Maybe PicocParse() will only run code which isn't inside any function?

Thanks a lot for developing Pico C, it works great for me!!!