예제 #1
0
PyObject *
PyObject_Unicode(PyObject *v)
{
	PyObject *res;
	PyObject *func;
	PyObject *str;
	static PyObject *unicodestr;

	if (v == NULL) {
		res = PyString_FromString("<NULL>");
		if (res == NULL)
			return NULL;
		str = PyUnicode_FromEncodedObject(res, NULL, "strict");
		Py_DECREF(res);
		return str;
	} else if (PyUnicode_CheckExact(v)) {
		Py_INCREF(v);
		return v;
	}
	/* XXX As soon as we have a tp_unicode slot, we should
	   check this before trying the __unicode__
	   method. */
	if (unicodestr == NULL) {
		unicodestr= PyString_InternFromString("__unicode__");
		if (unicodestr == NULL)
			return NULL;
	}
	func = PyObject_GetAttr(v, unicodestr);
	if (func != NULL) {
		res = PyEval_CallObject(func, (PyObject *)NULL);
		Py_DECREF(func);
	}
	else {
		PyErr_Clear();
		if (PyUnicode_Check(v)) {
			/* For a Unicode subtype that's didn't overwrite __unicode__,
			   return a true Unicode object with the same data. */
			return PyUnicode_FromUnicode(PyUnicode_AS_UNICODE(v),
			                             PyUnicode_GET_SIZE(v));
		}
		if (PyString_CheckExact(v)) {
			Py_INCREF(v);
			res = v;
		}
		else {
			if (v->ob_type->tp_str != NULL)
				res = (*v->ob_type->tp_str)(v);
			else
				res = PyObject_Repr(v);
		}
	}
	if (res == NULL)
		return NULL;
	if (!PyUnicode_Check(res)) {
		str = PyUnicode_FromEncodedObject(res, NULL, "strict");
		Py_DECREF(res);
		res = str;
	}
	return res;
}
예제 #2
0
파일: normalizer.c 프로젝트: eaudeweb/naaya
void CopyTranslationTable(Normalizer *self, PyObject *table) {
    
    int i;

    self->table = PyList_New(0);

    table = PySequence_Fast(table, "argument must be sequence"); 

    for (i=0; i<PyObject_Length(table); i++) {
        PyObject *item, *key, *value, *tp;

        item = PySequence_Fast_GET_ITEM(table, i);

        key   = PyTuple_GetItem(item,0);
        value = PyTuple_GetItem(item,1);

        if (PyString_Check(key))  
            key = PyUnicode_FromEncodedObject(key, self->encoding,"strict");
        else Py_XINCREF(key);

        if (PyString_Check(value)) 
            value = PyUnicode_FromEncodedObject(value, self->encoding,"strict");
        else Py_XINCREF(value);

        tp = Py_BuildValue("(OO)",key,value);
        PyList_Append(self->table, tp);
    
        Py_DECREF(tp);
        Py_DECREF(value);
        Py_DECREF(key);
    }

    Py_DECREF(table);
}
예제 #3
0
파일: cfield.c 프로젝트: nanwu/pyston
/* u - a single wchar_t character */
static PyObject *
u_set(void *ptr, PyObject *value, Py_ssize_t size)
{
    Py_ssize_t len;

    if (PyString_Check(value)) {
        value = PyUnicode_FromEncodedObject(value,
                                            _ctypes_conversion_encoding,
                                            _ctypes_conversion_errors);
        if (!value)
            return NULL;
    } else if (!PyUnicode_Check(value)) {
        PyErr_Format(PyExc_TypeError,
                        "unicode string expected instead of %s instance",
                        value->ob_type->tp_name);
        return NULL;
    } else
        Py_INCREF(value);

    len = PyUnicode_GET_SIZE(value);
    if (len != 1) {
        Py_DECREF(value);
        PyErr_SetString(PyExc_TypeError,
                        "one character unicode string expected");
        return NULL;
    }

    *(wchar_t *)ptr = PyUnicode_AS_UNICODE(value)[0];
    Py_DECREF(value);

    _RET(value);
}
예제 #4
0
파일: utils.c 프로젝트: KarapulYa/pyLDAP
/*	Converts a berval structure to a Python bytearray or if it's possible to string. */
PyObject *
berval2PyObject(struct berval *bval) {
	PyObject *bytes;
	PyObject *obj;

	bytes = PyBytes_FromStringAndSize(bval->bv_val, bval->bv_len);
	if (bytes == NULL) {
		PyErr_BadInternalCall();
		return NULL;
	}
	obj = PyUnicode_FromEncodedObject(bytes, NULL, NULL);
	/* Unicode converting is failed, set bytearray to return value. */
	if (obj == NULL) {
		obj = bytes;
	} else {
		Py_DECREF(bytes);
	}
	/* Check for errors. */
	if (PyErr_Occurred()) {
		/* Should be a reason why there is nothing about
		   PyExc_UnicodeDecodeError in the official documentation. */
		if (PyErr_ExceptionMatches(PyExc_UnicodeDecodeError) == 1) {
			/* UnicodeDecode error is excepted and will be ignored.*/
			PyErr_Clear();
		}
	}
	return obj;
}
예제 #5
0
/* Converts a Python 8-bit string to a unicode string object.  Assumes the
   8-bit string is in the host charset.  If an error occurs during conversion,
   returns NULL with a python exception set.

   As an added bonus, the functions accepts a unicode string and returns it
   right away, so callers don't need to check which kind of string they've
   got.  In Python 3, all strings are Unicode so this case is always the
   one that applies.

   If the given object is not one of the mentioned string types, NULL is
   returned, with the TypeError python exception set.  */
PyObject *
python_string_to_unicode (PyObject *obj)
{
  PyObject *unicode_str;

  /* If obj is already a unicode string, just return it.
     I wish life was always that simple...  */
  if (PyUnicode_Check (obj))
    {
      unicode_str = obj;
      Py_INCREF (obj);
    }
#ifndef IS_PY3K
  else if (PyString_Check (obj))
    unicode_str = PyUnicode_FromEncodedObject (obj, host_charset (), NULL);
#endif
  else
    {
      PyErr_SetString (PyExc_TypeError,
		       _("Expected a string or unicode object."));
      unicode_str = NULL;
    }

  return unicode_str;
}
예제 #6
0
파일: normalizer.c 프로젝트: eaudeweb/naaya
static PyObject *NormalizeWord(Normalizer *self,PyObject *word)
{
    int i;
    PyObject *temp;

    if (PyString_Check(word)) {
        if (! (temp = PyUnicode_FromEncodedObject(word,self->encoding,"strict"))) {
            PyErr_SetString(PyExc_UnicodeError,"unicode conversion failed");
            return NULL;
        }
    }  else  {
        temp = PyUnicode_FromObject(word);
    }

    for (i=0; i<PyList_Size(self->table); i++) {
        PyObject *s, *item, *key, *value;

        item = PySequence_Fast_GET_ITEM(self->table, i);

        key   = PyTuple_GetItem(item,0);
        value = PyTuple_GetItem(item,1);

        if (! (s = PyUnicode_Replace( temp, key, value, -1)))
            return NULL;

        Py_DECREF(temp);

        temp = s;
    }

    return temp;
}
예제 #7
0
static PyObject *
U_set(void *ptr, PyObject *value, Py_ssize_t length)
{
    Py_ssize_t size;

    /* It's easier to calculate in characters than in bytes */
    length /= sizeof(wchar_t);

    if (PyBytes_Check(value)) {
        value = PyUnicode_FromEncodedObject(value,
                                            _ctypes_conversion_encoding,
                                            _ctypes_conversion_errors);
        if (!value)
            return NULL;
    } else if (!PyUnicode_Check(value)) {
        PyErr_Format(PyExc_TypeError,
                        "unicode string expected instead of %s instance",
                        value->ob_type->tp_name);
        return NULL;
    } else
        Py_INCREF(value);
    size = PyUnicode_GET_SIZE(value);
    if (size > length) {
        PyErr_Format(PyExc_ValueError,
                     "string too long (%zd, maximum length %zd)",
                     size, length);
        Py_DECREF(value);
        return NULL;
    } else if (size < length-1)
        /* copy terminating NUL character if there is space */
        size += 1;
    PyUnicode_AsWideChar((PyUnicodeObject *)value, (wchar_t *)ptr, size);
    return value;
}
예제 #8
0
PyObject* JPyString::fromString(const char* str) 
{
#if PY_MAJOR_VERSION < 3
	PY_CHECK( PyObject* obj = PyString_FromString(str) );
	return obj;
#else
	PY_CHECK( PyObject* bytes = PyBytes_FromString(str) );
	PY_CHECK( PyObject* unicode = PyUnicode_FromEncodedObject(bytes, "UTF-8", "strict") );
	Py_DECREF(bytes);
	return unicode;
#endif

}
예제 #9
0
static gboolean
_pygi_marshal_from_py_unichar (PyObject          *py_arg,
                               GIArgument        *arg)
{
    Py_ssize_t size;
    gchar *string_;

    if (py_arg == Py_None) {
        arg->v_uint32 = 0;
        return FALSE;
    }

    if (PyUnicode_Check (py_arg)) {
       PyObject *py_bytes;

       size = PyUnicode_GET_SIZE (py_arg);
       py_bytes = PyUnicode_AsUTF8String (py_arg);
       if (!py_bytes)
           return FALSE;

       string_ = g_strdup(PYGLIB_PyBytes_AsString (py_bytes));
       Py_DECREF (py_bytes);

#if PY_VERSION_HEX < 0x03000000
    } else if (PyString_Check (py_arg)) {
       PyObject *pyuni = PyUnicode_FromEncodedObject (py_arg, "UTF-8", "strict");
       if (!pyuni)
           return FALSE;

       size = PyUnicode_GET_SIZE (pyuni);
       string_ = g_strdup (PyString_AsString(py_arg));
       Py_DECREF (pyuni);
#endif
    } else {
       PyErr_Format (PyExc_TypeError, "Must be string, not %s",
                     py_arg->ob_type->tp_name);
       return FALSE;
    }

    if (size != 1) {
       PyErr_Format (PyExc_TypeError, "Must be a one character string, not %lld characters",
                     (long long) size);
       g_free (string_);
       return FALSE;
    }

    arg->v_uint32 = g_utf8_get_char (string_);
    g_free (string_);

    return TRUE;
}
예제 #10
0
파일: cfield.c 프로젝트: nanwu/pyston
static PyObject *
BSTR_set(void *ptr, PyObject *value, Py_ssize_t size)
{
    BSTR bstr;

    /* convert value into a PyUnicodeObject or NULL */
    if (Py_None == value) {
        value = NULL;
    } else if (PyString_Check(value)) {
        value = PyUnicode_FromEncodedObject(value,
                                            _ctypes_conversion_encoding,
                                            _ctypes_conversion_errors);
        if (!value)
            return NULL;
    } else if (PyUnicode_Check(value)) {
        Py_INCREF(value); /* for the descref below */
    } else {
        PyErr_Format(PyExc_TypeError,
                        "unicode string expected instead of %s instance",
                        value->ob_type->tp_name);
        return NULL;
    }

    /* create a BSTR from value */
    if (value) {
        Py_ssize_t size = PyUnicode_GET_SIZE(value);
        if ((unsigned) size != size) {
            PyErr_SetString(PyExc_ValueError, "String too long for BSTR");
            return NULL;
        }
        bstr = SysAllocStringLen(PyUnicode_AS_UNICODE(value),
                                 (unsigned)size);
        Py_DECREF(value);
    } else
        bstr = NULL;

    /* free the previous contents, if any */
    if (*(BSTR *)ptr)
        SysFreeString(*(BSTR *)ptr);

    /* and store it */
    *(BSTR *)ptr = bstr;

    /* We don't need to keep any other object */
    _RET(value);
}
예제 #11
0
static PyObject *
Splitter_split(Splitter *self, PyObject *args)
{
    PyObject *doc;
    char *encoding = "iso-8859-15";

    Py_XDECREF(self->list);
    self->list = PyList_New(0);

    if (! (PyArg_ParseTuple(args,"O|s",&doc, &encoding))) return NULL;

    if (PyBytes_Check(doc)) {
        if (strlen(encoding) == 0 || !strcmp(encoding,"ascii"))
            splitString(self, doc);
        else {
            PyObject *doc1;
            if (! (doc1 = PyUnicode_FromEncodedObject(doc, encoding, "strict"))) {
                PyErr_SetString(PyExc_UnicodeError,"unicode conversion failed (maybe wrong encoding parameter)");
                return NULL;
            }

            splitUnicodeString(self, doc1);
            Py_XDECREF(doc1);
        }
    } else if (PyUnicode_Check(doc)) {
        PyObject *doc1; // create a *real* copy since we need to modify the string
        doc1 = PyUnicode_FromUnicode(NULL, PyUnicode_GET_SIZE(doc));
        Py_UNICODE_COPY(PyUnicode_AS_UNICODE(doc1),
                        PyUnicode_AS_UNICODE(doc),
                        PyUnicode_GET_SIZE(doc));
        splitUnicodeString(self, doc1);
        Py_DECREF(doc1);
    } else {
        PyErr_SetString(PyExc_TypeError, "first argument must be  string or unicode");
        return NULL;
    }

    Py_XINCREF(self->list);

    return self->list;
}
예제 #12
0
PYCURL_INTERNAL PyObject *
PyText_FromString_Ignore(const char *string)
{
    PyObject *v;

#if PY_MAJOR_VERSION >= 3
    PyObject *u;
    
    v = Py_BuildValue("y", string);
    if (v == NULL) {
        return NULL;
    }
    
    u = PyUnicode_FromEncodedObject(v, NULL, "replace");
    Py_DECREF(v);
    return u;
#else
    v = Py_BuildValue("s", string);
    return v;
#endif
}
예제 #13
0
파일: cfield.c 프로젝트: nanwu/pyston
static PyObject *
Z_set(void *ptr, PyObject *value, Py_ssize_t size)
{
    if (value == Py_None) {
        *(wchar_t **)ptr = NULL;
        Py_INCREF(value);
        return value;
    }
    if (PyString_Check(value)) {
        value = PyUnicode_FromEncodedObject(value,
                                            _ctypes_conversion_encoding,
                                            _ctypes_conversion_errors);
        if (!value)
            return NULL;
    } else if (PyInt_Check(value) || PyLong_Check(value)) {
#if SIZEOF_VOID_P == SIZEOF_LONG_LONG
        *(wchar_t **)ptr = (wchar_t *)PyInt_AsUnsignedLongLongMask(value);
#else
        *(wchar_t **)ptr = (wchar_t *)PyInt_AsUnsignedLongMask(value);
#endif
        Py_INCREF(Py_None);
        return Py_None;
    } else if (!PyUnicode_Check(value)) {
        PyErr_Format(PyExc_TypeError,
                     "unicode string or integer address expected instead of %s instance",
                     value->ob_type->tp_name);
        return NULL;
    } else
        Py_INCREF(value);
#ifdef HAVE_USABLE_WCHAR_T
    /* HAVE_USABLE_WCHAR_T means that Py_UNICODE and wchar_t is the same
       type.  So we can copy directly.  Hm, are unicode objects always NUL
       terminated in Python, internally?
     */
    *(wchar_t **)ptr = PyUnicode_AS_UNICODE(value);
    return value;
#else
    {
        /* We must create a wchar_t* buffer from the unicode object,
           and keep it alive */
        PyObject *keep;
        wchar_t *buffer;

        int size = PyUnicode_GET_SIZE(value);
        size += 1; /* terminating NUL */
        size *= sizeof(wchar_t);
        buffer = (wchar_t *)PyMem_Malloc(size);
        if (!buffer) {
            Py_DECREF(value);
            return PyErr_NoMemory();
        }
        memset(buffer, 0, size);
        keep = CAPSULE_NEW(buffer, CTYPES_CAPSULE_WCHAR_T);
        if (!keep) {
            Py_DECREF(value);
            PyMem_Free(buffer);
            return NULL;
        }
        *(wchar_t **)ptr = (wchar_t *)buffer;
        if (-1 == PyUnicode_AsWideChar((PyUnicodeObject *)value,
                                       buffer, PyUnicode_GET_SIZE(value))) {
            Py_DECREF(value);
            Py_DECREF(keep);
            return NULL;
        }
        Py_DECREF(value);
        return keep;
    }
#endif
}
예제 #14
0
 // encode_string_unaryfunc/py_encode_string -- manufacture a unaryfunc
 // "slot" which encodes a Python string using the default encoding
 extern "C" PyObject* encode_string_unaryfunc(PyObject* x)
 {
     return PyUnicode_FromEncodedObject( x, 0, 0 );
 }
예제 #15
0
static PyObject *
newSplitter(PyObject *modinfo, PyObject *args,PyObject *keywds)
{
    Splitter *self=NULL;
    PyObject *doc=NULL, *unicodedoc=NULL,*synstop=NULL;
    char *encoding = "latin1";
    int index_numbers = 0;
    int max_len=64;
    int single_char = 0;
    int casefolding=1;

    if (! (PyArg_ParseTupleAndKeywords(args,keywds,"O|Osiiii",splitter_args,&doc,&synstop,&encoding,&index_numbers,&single_char,&max_len,&casefolding))) return NULL;

#ifdef DEBUG
    puts("got text");
    PyObject_Print(doc,stdout,0);
    fflush(stdout);
#endif

    if (index_numbers<0 || index_numbers>1) {
        PyErr_SetString(PyExc_ValueError,"indexnumbers must be 0 or 1");
        return NULL;
    }

    if (casefolding<0 || casefolding>1) {
        PyErr_SetString(PyExc_ValueError,"casefolding must be 0 or 1");
        return NULL;
    }

    if (single_char<0 || single_char>1) {
        PyErr_SetString(PyExc_ValueError,"singlechar must be 0 or 1");
        return NULL;
    }

    if (max_len<1 || max_len>128) {
        PyErr_SetString(PyExc_ValueError,"maxlen must be between 1 and 128");
        return NULL;
    }

    if (PyString_Check(doc)) {

        unicodedoc = PyUnicode_FromEncodedObject(doc,encoding,"strict");
        if (unicodedoc ==NULL) {
            PyErr_SetString(PyExc_UnicodeError, "Problem converting encoded string");
            return NULL;
        }

    } else if( PyUnicode_Check(doc)) {
        unicodedoc = doc;
        Py_INCREF(unicodedoc);

    } else {
        PyErr_SetString(PyExc_TypeError, "first argument is neither string nor unicode.");
        return NULL;
    }

    if (! (self = PyObject_NEW(Splitter, &SplitterType))) return NULL;

    if (synstop) {
        self->synstop = synstop;
        Py_INCREF(synstop);
    } else  self->synstop=NULL;

    self->index_numbers      = index_numbers;
    self->max_len            = max_len;
    self->allow_single_chars = single_char;
    self->casefolding        = casefolding;

    if ((splitUnicodeString(self,(PyUnicodeObject *)unicodedoc)) < 0)
      goto err;

    Py_DECREF(unicodedoc);
    return (PyObject*)self;

err:
    Py_DECREF(self);
    Py_DECREF(unicodedoc);

    return NULL;
}
예제 #16
0
static PyObject *object_to_string(PyObject *object)
{
  PyObject *result = NULL;

  if (PyUnicode_Check(object)) {
    Py_INCREF(object);
    result = object;
  }
  
  else if (PyString_Check(object)) {
    /* Python DOM binding: string objects must be UTF-8 */
    result = PyUnicode_FromEncodedObject(object, "UTF-8", "strict");
  }

  else if (PyFloat_Check(object)) {
    double d = PyFloat_AS_DOUBLE(object);
    if (PyNumber_Finite(object)) {
      if (floor(d) == d) {
        /* Format as integer */
        PyObject *num = PyNumber_Long(object);
        if (!num)
          return NULL;
        result = PyObject_Unicode(num);
        Py_DECREF(num);
      } 
      else {
        /* worst case length calc to ensure no buffer overrun:
           fmt = %#.<prec>g
           buf = '-' + [0-9]*prec + '.' + 'e+' + (longest exp for 
                                                  any double rep.) 
           len = 1 + prec + 1 + 2 + 5 = 9 + prec
           If prec=0 the effective precision is 1 (the leading digit is
           always given), therefore increase by one to 10+prec. 
        */
        char buf[32]; /* only 10 + 12 + '\0' is needed, more than enough */
        int len;
        len = sprintf(buf, "%0.12g", d);
        result = PyUnicode_DecodeASCII(buf, len, "strict");
      }
    }
    else if (PyNumber_IsNaN(object)) {
      result = PyUnicode_DecodeASCII("NaN", 3, "strict");
    }
    else if (d < 0) {
      result = PyUnicode_DecodeASCII("-Infinity", 9, "strict");
    }
    else {
      result = PyUnicode_DecodeASCII("Infinity", 8, "strict");
    }
  }

  else if (PyBoolean_Check(object)) {
    if (PyObject_IsTrue(object))
      result = PyUnicode_DecodeASCII("true", 4, "strict");
    else
      result = PyUnicode_DecodeASCII("false", 5, "strict");
  }

  else if (PyInt_Check(object) || PyLong_Check(object)) {
    result = PyObject_Unicode(object);
  }

  else if (PyList_Check(object)) {
    if (PyList_GET_SIZE(object)) 
      result = object_to_string(PyList_GET_ITEM(object, 0));
    else
      result = PyUnicode_FromUnicode(NULL, 0);
  }

  else {
    /* check for pre-computed string value */
    result = PyObject_GetAttrString(object, "stringValue");
    if (result == NULL) {
      /* assume a DOM node, node_to_string() returns empty string if not */
      PyErr_Clear();
      result = node_to_string(object);
    }
  }
  return result;
}
예제 #17
0
NUITKA_MAY_BE_UNUSED static PyObject *TO_UNICODE3( PyObject *value, PyObject *encoding, PyObject *errors )
{
    CHECK_OBJECT( value );
    if ( encoding ) CHECK_OBJECT( encoding );
    if ( errors ) CHECK_OBJECT( errors );

    char *encoding_str;

    if ( encoding == NULL )
    {
        encoding_str = NULL;
    }
    else if ( Nuitka_String_Check( encoding ) )
    {
        encoding_str = Nuitka_String_AsString_Unchecked( encoding );
    }
#if PYTHON_VERSION < 300
    else if ( PyUnicode_Check( encoding ) )
    {
        PyObject *uarg2 = _PyUnicode_AsDefaultEncodedString( encoding, NULL );
        CHECK_OBJECT( uarg2 );

        encoding_str = Nuitka_String_AsString_Unchecked( uarg2 );
    }
#endif
    else
    {
        PyErr_Format( PyExc_TypeError, "unicode() argument 2 must be string, not %s", Py_TYPE( encoding )->tp_name );
        return NULL;
    }

    char *errors_str;

    if ( errors == NULL )
    {
        errors_str = NULL;
    }
    else if ( Nuitka_String_Check( errors ) )
    {
        errors_str = Nuitka_String_AsString_Unchecked( errors );
    }
#if PYTHON_VERSION < 300
    else if ( PyUnicode_Check( errors ) )
    {
        PyObject *uarg3 = _PyUnicode_AsDefaultEncodedString( errors, NULL );
        CHECK_OBJECT( uarg3 );

        errors_str = Nuitka_String_AsString_Unchecked( uarg3 );
    }
#endif
    else
    {
        PyErr_Format( PyExc_TypeError, "unicode() argument 3 must be string, not %s", Py_TYPE( errors )->tp_name );
        return NULL;
    }

    PyObject *result = PyUnicode_FromEncodedObject( value, encoding_str, errors_str );

    if (unlikely( result == NULL ))
    {
        return NULL;
    }

    assert( PyUnicode_Check( result ) );

    return result;
}
예제 #18
0
파일: utils.c 프로젝트: charrea6/kaa-base
PyObject *listdir(PyObject *self, PyObject *args)
{
    char *name = NULL;
    PyObject *d, *v;
    DIR *dirp;
    struct dirent *ep;
    int arg_is_unicode = 1;

    errno = 0;
    if (!PyArg_ParseTuple(args, "U:listdir", &v)) {
        arg_is_unicode = 0;
        PyErr_Clear();
    }
    if (!PyArg_ParseTuple(args, "et:listdir", Py_FileSystemDefaultEncoding, &name))
        return NULL;
    if ((dirp = opendir(name)) == NULL) {
        return posix_error_with_allocated_filename(name);
    }
    if ((d = PyList_New(0)) == NULL) {
        closedir(dirp);
        PyMem_Free(name);
        return NULL;
    }
    for (;;) {
        errno = 0;
        Py_BEGIN_ALLOW_THREADS
        ep = readdir(dirp);
        Py_END_ALLOW_THREADS
        if (ep == NULL) {
            if (errno == 0) {
                break;
            } else {
                closedir(dirp);
                Py_DECREF(d);
                return posix_error_with_allocated_filename(name);
            }
        }
        if (ep->d_name[0] == '.' &&
            (NAMLEN(ep) == 1 ||
             (ep->d_name[1] == '.' && NAMLEN(ep) == 2)))
            continue;
        v = PyString_FromStringAndSize(ep->d_name, NAMLEN(ep));
        if (v == NULL) {
            Py_DECREF(d);
            d = NULL;
            break;
        }
#ifdef Py_USING_UNICODE
        if (arg_is_unicode) {
            PyObject *w;

            w = PyUnicode_FromEncodedObject(v,
                    Py_FileSystemDefaultEncoding,
                    "strict");
            if (w != NULL) {
                Py_DECREF(v);
                v = w;
            }
            else {
                /* fall back to the original byte string, as
                   discussed in patch #683592 */
                PyErr_Clear();
            }
        }
#endif
        if (PyList_Append(d, v) != 0) {
            Py_DECREF(v);
            Py_DECREF(d);
            d = NULL;
            break;
        }
        Py_DECREF(v);
    }
    closedir(dirp);
    PyMem_Free(name);

    return d;
}
wxString* newWxStringFromPy( PyObject* src )
{
    bool        must_unref_str = false;

    wxString*   result  = NULL;
    PyObject*   obj     = src;

#if wxUSE_UNICODE
    bool        must_unref_obj = false;
    // Unicode string to python unicode string
    PyObject*   uni_str = src;

    // if not an str or unicode, try to str(src)
#if PY_MAJOR_VERSION >= 3
    if( !PyBytes_Check( src ) && !PyUnicode_Check( src ) )
#else
    if( !PyString_Check( src ) && !PyUnicode_Check( src ) )
#endif
    {
        obj = PyObject_Str( src );

#if PY_MAJOR_VERSION >= 3
        uni_str = obj; // in case of Python 3 our string is already correctly encoded
#endif

        must_unref_obj = true;

        if( PyErr_Occurred() )
            return NULL;
    }

#if PY_MAJOR_VERSION >= 3
    if( PyBytes_Check( obj ) )
#else
    if( PyString_Check( obj ) )
#endif
    {
        uni_str = PyUnicode_FromEncodedObject( obj, wxPythonEncoding, "strict" );
        must_unref_str = true;

        if( PyErr_Occurred() )
            return NULL;
    }

    result = new wxString();
#if PY_MAJOR_VERSION >= 3
    size_t len = PyUnicode_GET_LENGTH( uni_str );
#else
    size_t len = PyUnicode_GET_SIZE( uni_str );
#endif

    if( len )
    {
#if PY_MAJOR_VERSION >= 3
        PyUnicode_AsWideChar( uni_str,
                              wxStringBuffer( *result, len ), len );
#else
        PyUnicode_AsWideChar( (PyUnicodeObject*) uni_str,
                              wxStringBuffer( *result, len ), len );
#endif
    }

    if( must_unref_str )
    {
        Py_DECREF( uni_str );
    }

    if( must_unref_obj )
    {
        Py_DECREF( obj );
    }

#else
    // normal string (or object) to normal python string
    PyObject* str = src;

    if( PyUnicode_Check( src ) )    // if it's unicode convert to normal string
    {
        str = PyUnicode_AsEncodedString( src, wxPythonEncoding, "strict" );

        if( PyErr_Occurred() )
            return NULL;
    }
#if PY_MAJOR_VERSION >= 3
    else if( !PyUnicode_Check( src ) )
#else
    else if( !PyString_Check( src ) )    // if it's not a string, str(obj)
#endif
    {
        str = PyObject_Str( src );
        must_unref_str = true;

        if( PyErr_Occurred() )
            return NULL;
    }

    // get the string pointer and size
    char*       str_ptr;
    Py_ssize_t  str_size;
    PyString_AsStringAndSize( str, &str_ptr, &str_size );

    // build the wxString from our pointer / size
    result = new wxString( str_ptr, str_size );

    if( must_unref_str )
    {
        Py_DECREF( str );
    }

#endif

    return result;
}