Skip to content

Instantly share code, notes, and snippets.

@framkant
Last active August 29, 2015 14:11

Revisions

  1. framkant revised this gist Dec 16, 2014. 1 changed file with 2 additions and 0 deletions.
    2 changes: 2 additions & 0 deletions Hotload
    Original file line number Diff line number Diff line change
    @@ -1,3 +1,5 @@
    // made by @filipwanstrom
    // public domain / as is

    // The main.c file
    #include <stdio.h>
  2. framkant created this gist Dec 16, 2014.
    104 changes: 104 additions & 0 deletions Hotload
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,104 @@

    // The main.c file
    #include <stdio.h>
    #include <dlfcn.h>
    #include <sys/stat.h>
    #include <unistd.h>

    typedef void (*printfunc)(void);

    struct Reloadable {
    char filename[256];
    char symname[256];
    printfunc func;
    void* lib;
    time_t last_modified;
    };


    time_t get_mod_time(const char* filename)
    {
    struct stat file_stat;
    stat(filename, &file_stat);
    return file_stat.st_mtime;
    }

    void bind_lib(struct Reloadable* r){
    if(r->lib == NULL) {
    void* f = dlopen(r->filename, RTLD_LAZY);
    if(f != NULL) {
    r->lib = f;
    }
    }else {
    // unload lib first
    dlclose(r->lib);
    void* f = dlopen(r->filename, RTLD_LAZY);
    if(f != NULL) {
    r->lib = f;
    }
    }
    void *func = dlsym(r->lib, r->symname);
    if (func != NULL) {
    r->func = (printfunc)(func);
    }

    }

    void reload_if_modified(struct Reloadable * reloadable)
    {
    time_t n = get_mod_time(reloadable->filename);
    if(n>reloadable->last_modified) {
    reloadable->last_modified = n;
    bind_lib(reloadable);
    }
    }

    void printstuff(struct Reloadable * r)
    {
    if(r->lib !=NULL && r->func != NULL ) {
    r->func();
    }

    }

    int main (int argc, char **argv)
    {
    printf("Loading hotreload host\n");

    struct Reloadable reloadable = {
    "printfuncs.dylib",
    "printstuff", NULL, NULL, 0
    };
    reloadable.last_modified = get_mod_time(reloadable.filename);
    bind_lib(&reloadable);
    while(1) {
    sleep(1);
    printstuff(&reloadable);
    reload_if_modified(&reloadable);

    }

    return 1;
    }

    // the printfuncs.c file
    #include <stdio.h>
    void printstuff()
    {
    printf("love is everything\n");
    }

    // the makefile
    all: printfuncs hotreload

    printfuncs:
    clang -dynamiclib printfuncs.c -o printfuncs.dylib

    hotreload:
    clang main.c -o hotreload

    clean:
    rm -rf hotreload printfuncs.dylib