Is there any way to compile additional code at runtime in C or C++?

后端 未结 6 2000
执笔经年
执笔经年 2020-12-24 02:45

Here is what I want to do:

  1. Run a program and initialize some data structures.
  2. Then compile additional code that can access/modify the existing data st
6条回答
  •  不知归路
    2020-12-24 03:26

    There is one simple solution:

    1. create own library having special functions
    2. load created library
    3. execute functions from that library, pass structures as function variables

    To use your structures you have to include same header files like in host application.

    structs.h:

    struct S {
        int a,b;
    };
    

    main.cpp:

    #include 
    #include 
    #include 
    #include 
    
    #include "structs.h"
    
    using namespace std;
    
    int main ( int argc, char **argv ) {
    
        // create own program
        ofstream f ( "tmp.cpp" );
        f << "#include\n#include \"structs.h\"\n extern \"C\" void F(S &s) { s.a += s.a; s.b *= s.b; }\n";
        f.close();
    
        // create library
        system ( "/usr/bin/gcc -shared tmp.cpp -o libtmp.so" );
    
        // load library        
        void * fLib = dlopen ( "./libtmp.so", RTLD_LAZY );
        if ( !fLib ) {
            cerr << "Cannot open library: " << dlerror() << '\n';
        }
    
        if ( fLib ) {
            int ( *fn ) ( S & ) = dlsym ( fLib, "F" );
    
            if ( fn ) {
                for(int i=0;i<11;i++) {
                    S s;
                    s.a = i;
                    s.b = i;
    
                    // use function
                    fn(s);
                    cout << s.a << " " << s.b << endl;
                }
            }
            dlclose ( fLib );
        }
    
        return 0;
    }
    

    output:

    0 0
    2 1
    4 4
    6 9
    8 16
    10 25
    12 36
    14 49
    16 64
    18 81
    20 100
    

    You can also create mutable program that will be changing itself (source code), recompiling yourself and then replace it's actual execution with execv and save resources with shared memory.

提交回复
热议问题