title: ctypes how to pass string from python to c++ function, and how to return string from c++ function to python
body: <p>I want to call a c++ function from python, this c++ function takes char* as parameter, and return string. Below is my code.</p>
  
  <p>wrapper.cpp</p>
  
  <pre><code>#include &lt;Python.h&gt;
  #include &lt;string&gt;
  #include &lt;iostream&gt;
  
  using namespace std;
  
  extern "C"
  string return_string(char* name){
      cout&lt;&lt;strlen(name)&lt;&lt;endl;
      cout&lt;&lt;name&lt;&lt;endl;
      string s = "hello ";
      s += name;
      return s;
  }
  </code></pre>
  
  <p>compile wrapper.cpp to example.so</p>
  
  <pre><code>g++ -fPIC wrapper.cpp -o example.so -shared -I/usr/include/python2.7/
  </code></pre>
  
  <p>wrapper.py</p>
  
  <pre><code>import os
  from ctypes import *
  
  lib = cdll.LoadLibrary('./example.so')
  lib.return_string.restype = c_char_p
  lib.return_string.argtypes = [c_char_p]
  name = create_string_buffer("Tom")
  s = lib.return_string(name);
  print s
  print name
  </code></pre>
  
  <p>here is my output</p>
  
  <pre><code>18
  ��H�L�l���A���
  1
  &lt;ctypes.c_char_Array_4 object at 0x7f5f480be710&gt;
  </code></pre>
  
  <p>How to make it works? </p>