SWIG return unsigned char * from C to Python
<p>I'm running into a problem with generating an interface for python with underlying C code.
I have the following pieces of code:</p>

<p>prov.h</p>

<pre><code>#include&lt;string.h&gt;
#include&lt;stdio.h&gt;
#include&lt;stdlib.h&gt;

unsigned char *out();
</code></pre>

<p>prov.c</p>

<pre><code>#include "prov.h"

unsigned char *out()
{
    unsigned char *bytes="Hello";
    unsigned char *data=NULL;
    data=calloc(6,sizeof(char));
    if(data) {
        strncpy(data,bytes,6);
    }
    return data;
}
</code></pre>

<p>prov.i</p>

<pre><code>%module prov
%{
#include "prov.h"
%}

unsigned char *out();
</code></pre>

<p>And I generate the .so as shown below:</p>

<pre><code>$ swig -python prov.i
$ gcc -fpic -c prov.c  prov_wrap.c -I/usr/include/python2.7
$ gcc -shared prov.o prov_wrap.o -o _prov.so
$ python
Python 2.7.3 (default, Jun 22 2015, 19:33:41) 
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
&gt;&gt;&gt; 
&gt;&gt;&gt; import prov
&gt;&gt;&gt; s=prov.out()
&gt;&gt;&gt; s
&lt;Swig Object of type 'unsigned char *' at 0x7fb241dbff90&gt;
</code></pre>

<p>Now the problem is that when I try to view the returned string, s from my C function, it doesn't seem to show it as a python string object (I expected when I print s the output should be 'Hello'). Can anyone please help me out with returning unsigned char * to python calling code?</p>

<p>Either return <code>char*</code> instead, or you can apply the <code>char*</code> typemaps to <code>unsigned char*</code>.  You'll also want <code>%newobject</code> to let Python know to free the returned pointer after converting the return result to a Python object.</p>

<pre><code>%module prov
%{
#include "prov.h"
%}

%apply char* {unsigned char*};    
%newobject out;
unsigned char *out();
</code></pre>

python c swig