Search code examples
pythonswigswig-typemap

SWIG return bytes instead of string with typemap


I have two functions in my C library:

void passBytes(char *data, int size);
void returnBytes(char **data, int *size); //dynamically allocates

I successfully implement the wrapper for the first function using this post:

%typemap(in) (char *data, int size) {
  Py_ssize_t len;
  PyBytes_AsStringAndSize($input, &$1, &len);
  $2 = (int)len;
}

But can't figure out how to implement the second wrapper with typemaps. Can't use SWIG_PYTHON_STRICT_BYTE_CHAR because I need mix of str and bytes.


Solution

  • You are almost there

    %typemap(in, numinputs=0) (char **data) (char *temp) {
      $1 = &temp;
    }
    %typemap(argout) (char **data) {
      if (*$1) {
        $result = PyUnicode_FromString(*$1);
        free(*$1);
      }
    }
    

    Note that the two typemaps combined do the job. The length is not needed if the character array is null terminated. The parameter temp is created and the reference to this is passed to your C function allocating the array.