title: c++ call object method using pointer
body: <p>I created a shared lib, in which I defined a class Foo. In class Foo, there is a function named sayHi(). My question is once I created a Foo object foo, how can I call sayHi() of it. I put my code here.</p>
  
  <p>mylib.h</p>
  
  <pre><code>#ifndef FUNTEST_MYLIB_H
  #define FUNTEST_MYLIB_H
  
  
  class Foo {
  public:
      int id = 0;
      void sayHi();
  };
  
  
  #endif //FUNTEST_MYLIB_H
  </code></pre>
  
  <p>mylib.cpp</p>
  
  <pre><code>#include &lt;iostream&gt;
  #include "mylib.h"
  
  using namespace std;
  
  void Foo::sayHi()
  {
      cout &lt;&lt; "Implemented by lib" &lt;&lt; endl;
      cout &lt;&lt; "id is: " &lt;&lt; id &lt;&lt; endl;
  }
  
  Foo* create()
  {
      return new Foo();
  }
  </code></pre>
  
  <p>then I use the following commands compile the shared lib:</p>
  
  <pre><code>g++ -c -std=gnu++11 -fPIC mylib.cpp
  g++ -shared -fPIC -o mylib.so mylib.o
  </code></pre>
  
  <p>At the client side, I write two files:</p>
  
  <p>mylib2.cpp</p>
  
  <pre><code>#include &lt;iostream&gt;
  #include "mylib.h"
  
  using namespace std;
  
  void Foo::sayHi() {
      cout &lt;&lt; "Implemented by caller" &lt;&lt; endl;
      cout &lt;&lt; "id is: " &lt;&lt; id &lt;&lt; endl;
  }
  </code></pre>
  
  <p>main.cpp</p>
  
  <pre><code>#include &lt;iostream&gt;
  #include &lt;dlfcn.h&gt;
  #include "mylib.h"
  
  using namespace std;
  
  Foo* (*create)();
  void (*sayHi)();
  int main() {
      void* lib = dlopen("./mylib.so", RTLD_LAZY);
      create = (Foo* (*)())dlsym(lib, "_Z6createv");
      sayHi = (void (*)())dlsym(lib, "_ZN3Foo5sayHiEv");
  
      Foo* foo = create();
  
      sayHi();
      foo-&gt;sayHi();
  
      foo-&gt;id = 100;
      cout &lt;&lt; "Set id to " &lt;&lt; foo-&gt;id &lt;&lt; endl;
  
      /*
       *
       * how can I make the follow statement 'sayHi();'
       * output the following content:
       * Implemented by lib
       * id is: 100
       */
      sayHi(); // line 29, FIXME
      foo-&gt;sayHi();
  
      return 0;
  }
  </code></pre>
  
  <p>compile the client with following command:</p>
  
  <pre><code>g++ -std=gnu++11 main.cpp mylib.h mylib2.cpp -ldl
  </code></pre>
  
  <p>finally run the client:
  ./a.out</p>
  
  <p>the output is:</p>
  
  <pre><code>Implemented by lib
  id is: 0
  Implemented by caller
  id is: 0
  Set id to 100
  Implemented by lib
  id is: -1407102376 // FIXME
  Implemented by caller
  id is: 100
  </code></pre>
  
  <p>how can I make the statement 'sayHi();' at line 29 output the following content:</p>
  
  <pre><code>Implemented by lib 
  id is: 100
  </code></pre>
  
  <p>I know if i call the sayHi() function directly, without the foo object, the output will be wrong. But how can I fix it?</p>