How would a loaded library function call a symbol in the main application?

后端 未结 3 1376
春和景丽
春和景丽 2020-12-25 09:15

When loaded a shared library is opened via the function dlopen(), is there a way for it to call functions in main program?

3条回答
  •  一整个雨季
    2020-12-25 09:46

    Yes, If you provide your library a pointer to that function, I'm sure the library will be able to run/execute the function in the main program.

    Here is an example, haven't compiled it so beware ;)

    /* in main app */
    
    /* define your function */
    
    int do_it( char arg1, char arg2);
    
    int do_it( char arg1, char arg2){
      /* do it! */
      return 1;
    }
    
    /* some where else in main app (init maybe?) provide the pointer */
     LIB_set_do_it(&do_it);
    /** END MAIN CODE ***/
    
    /* in LIBRARY */
    
    int (*LIB_do_it_ptr)(char, char) = NULL;
    
    void LIB_set_do_it( int (*do_it_ptr)(char, char) ){
        LIB_do_it_ptr = do_it_ptr;
    }
    
    int LIB_do_it(){
      char arg1, arg2;
    
      /* do something to the args 
      ...
      ... */
    
      return LIB_do_it_ptr( arg1, arg2);
    }
    

提交回复
热议问题