How can I add reflection to a C++ application?

前端 未结 28 2141
感动是毒
感动是毒 2020-11-21 11:25

I\'d like to be able to introspect a C++ class for its name, contents (i.e. members and their types) etc. I\'m talking native C++ here, not managed C++, which has reflection

28条回答
  •  萌比男神i
    2020-11-21 11:47

    If you declare a pointer to a function like this:

    int (*func)(int a, int b);
    

    You can assign a place in memory to that function like this (requires libdl and dlopen)

    #include 
    
    int main(void)
    {
        void *handle;
        char *func_name = "bla_bla_bla";
        handle = dlopen("foo.so", RTLD_LAZY);
        *(void **)(&func) = dlsym(handle, func_name);
        return func(1,2);
    }
    

    To load a local symbol using indirection, you can use dlopen on the calling binary (argv[0]).

    The only requirement for this (other than dlopen(), libdl, and dlfcn.h) is knowing the arguments and type of the function.

提交回复
热议问题