title: C Method returning string to Python via ctypes
body: <p>Few years ago I had to create a python wrapper for a C library. My knowledge of C is very limited but I managed to create what was needed.
  Suddenly one method started causing issues, my only guess is it has to do something with python update.</p>
  
  <p>In any case, I had the following C code:</p>
  
  <pre><code>const char * myFunction()
  {
      return "My String";
  }
  
  DLL_EXPORT const char*
  test()
  {
      return myFunction();
  }
  </code></pre>
  
  <p>which in my Python wrapper was called using the following method:</p>
  
  <pre><code>def test(self):
          ret = self.lib.test()
  
          return c_char_p(ret).value
  </code></pre>
  
  <p>As stated before, this was working well, although I'm not really sure why given what I've recently discovered while trying to fix it.</p>
  
  <p>Currently that I'm getting 'Seg Fault' from python when calling the method test().</p>
  
  <p>Using this threads:</p>
  
  <p><a href="https://stackoverflow.com/questions/14883853/ctypes-return-a-string-from-c-function">ctypes return a string from c function</a></p>
  
  <p><a href="https://stackoverflow.com/questions/1788655/when-to-use-malloc-for-char-pointers?rq=1">When to use malloc for char pointers</a></p>
  
  <p>I managed to fix my code which now looks like this, c:</p>
  
  <pre><code>const char * myFunction()
  {
      return "My String";
  }
  
  DLL_EXPORT const char*
  test()
  {
      const char* st = myFunction();
      char *bar = _strdup(st);
  
      return bar;
  }
  </code></pre>
  
  <p>The python code remains the same. As said before, my knowledge of C is very limited and hence few questions:</p>
  
  <ol>
  <li>any idea why the old implementation was working and suddenly stopped? Was there some python update that could have had affected it?</li>
  <li>why in my c test() function  do I have to do _strdup(st) and return bar instead of simply returning st?</li>
  </ol>