コード例 #1
0
ファイル: ae.c プロジェクト: AdminCNP/appscript
static int AE_GetCFStringRef(PyObject *v, CFStringRef *p_itself)
{
	if (v == Py_None) { *p_itself = NULL; return 1; }
	if (PyBytes_Check(v)) {
	    char *cStr;
	    if (!PyArg_Parse(v, "es", "ascii", &cStr))
	    	return 0;
		*p_itself = CFStringCreateWithCString((CFAllocatorRef)NULL, cStr, kCFStringEncodingASCII);
		PyMem_Free(cStr);
		return 1;
	}
	if (PyUnicode_Check(v)) {
#ifdef Py_UNICODE_WIDE
	CFIndex size = PyUnicode_GET_DATA_SIZE(v);
	UTF32Char *unichars = PyUnicode_AsUnicode(v);
	*p_itself = CFStringCreateWithBytes((CFAllocatorRef)NULL,
										unichars,
										size,
										kCFStringEncodingUTF32, // 10.4+
										false); // ?
#else
		CFIndex size = PyUnicode_GetSize(v);
		UniChar *unichars = PyUnicode_AsUnicode(v);
		if (!unichars) return 0;
		*p_itself = CFStringCreateWithCharacters((CFAllocatorRef)NULL, unichars, size);
#endif
		return 1;
	}
	PyErr_SetString(PyExc_TypeError, "str/unicode required");
	return 0;
}
コード例 #2
0
ファイル: converters.c プロジェクト: vrai/Fudge-PyC
int fudgepyc_convertPythonToString ( FudgeString * target, PyObject * source )
{
    FudgeStatus status;
    if ( PyString_Check ( source ) )
    {
        status = FudgeString_createFromASCII ( target,
                                               PyString_AS_STRING ( source ),
                                               PyString_GET_SIZE ( source ) );
        return exception_raiseOnError ( status );
    }
    else if ( PyUnicode_Check ( source ) )
    {
        /* The Python docs specify that the internal representation of Unicode
           objects is either UCS2 or UCS4 */
        switch ( sizeof ( Py_UNICODE ) )
        {
            case 2:
                status = FudgeString_createFromUTF16 (
                             target,
                             ( fudge_byte * ) PyUnicode_AS_DATA ( source ),
                             PyUnicode_GET_DATA_SIZE ( source ) );
                break;

            case 4:
                status = FudgeString_createFromUTF32 (
                             target,
                             ( fudge_byte * ) PyUnicode_AS_DATA ( source ),
                             PyUnicode_GET_DATA_SIZE ( source ) );
                break;

            default:
                exception_raise_any ( PyExc_RuntimeError,
                                     "Cannot encode Python string; Python "
                                     "interpreter not using UCS2 or UCS4 for"
                                     "internal unicode encoding" );
                return -1;
        }
        return exception_raiseOnError ( status );
    }
    else
    {
        exception_raise_any ( PyExc_ValueError,
                              "Cannot use object as string (must be String "
                              "or Unicode)" );
        return -1;
    }
}
コード例 #3
0
void AppendPyUnicode(CBBString* aInto, PyObject* aObject)
{
	if (aObject) {
		python_ptr<PyObject> str(PyObject_Unicode(aObject));
		if (PyUnicode_Check(str.get())) {
			int bytes=PyUnicode_GET_DATA_SIZE(str.get());
			aInto->Append( TPtrC( 
				(const TUint16*)PyUnicode_AS_UNICODE(str.get()), bytes/2) );
		} else {
			aInto->Append(_L("[could not convert to unicode]"));
		}
	} else {
		aInto->Append(_L("None"));
	}
}
コード例 #4
0
ファイル: converters.c プロジェクト: vrai/Fudge-PyC
int fudgepyc_convertPythonToByteArray ( fudge_byte * * target,
                                        fudge_i32 * targetsize,
                                        PyObject * source )
{
    if ( PyString_Check ( source ) )
    {
        *targetsize = ( fudge_i32 ) PyString_GET_SIZE ( source );
        *target = ( fudge_byte * ) PyMem_Malloc ( *targetsize );
        if ( ! *target )
            return -1;
        memcpy ( *target, PyString_AS_STRING ( source ), *targetsize );
    }
    else if ( PyUnicode_Check ( source ) )
    {
        *targetsize = ( fudge_i32 ) PyUnicode_GET_DATA_SIZE ( source );
        *target = ( fudge_byte * ) PyMem_Malloc ( *targetsize );
        if ( ! *target )
            return -1;
        memcpy ( *target, PyUnicode_AS_DATA ( source ), *targetsize );
    }
    else if ( PySequence_Check ( source ) )
    {
        *targetsize = ( fudge_i32 ) PySequence_Size ( source );
        *target = ( fudge_byte * ) PyMem_Malloc ( *targetsize );
        if ( ! *target )
            return -1;

        if ( fudgepyc_convertPythonSeqToByteBlock ( *target,
                                                    *targetsize,
                                                    source ) )
        {
            PyMem_Free ( *target );
            return -1;
        }
    }
    else
    {
        exception_raise_any ( PyExc_ValueError,
                              "Only String, Unicode and sequence objects "
                              "can be converted in to byte arrays" );
        return -1;
    }
    return 0;
}
コード例 #5
0
ファイル: converters.c プロジェクト: vrai/Fudge-PyC
int fudgepyc_convertPythonToFixedByteArray ( fudge_byte * target,
                                             fudge_i32 size,
                                             PyObject * source )
{
    size_t actualsize;

    if ( PyString_Check ( source ) )
    {
        if ( ( actualsize = PyString_GET_SIZE ( source ) ) != size )
            goto size_mismatch;
        memcpy ( target, PyString_AS_STRING ( source ), size );
    }
    else if ( PyUnicode_Check ( source ) )
    {
        if ( ( actualsize = PyUnicode_GET_DATA_SIZE ( source ) ) != size )
            goto size_mismatch;
        memcpy ( target, PyUnicode_AS_DATA ( source ), size );
    }
    else if ( PySequence_Check ( source ) )
    {
        if ( ( actualsize = PySequence_Size ( source ) ) != size )
            goto size_mismatch;
        if ( fudgepyc_convertPythonSeqToByteBlock ( target, size, source ) )
            return -1;
    }
    else
    {
        exception_raise_any ( PyExc_ValueError,
                              "Only String, Unicode and sequence objects "
                              "can be converted in to fixed byte arrays" );
        return -1;
    }
    return 0;

size_mismatch:
    exception_raise_any (
        PyExc_ValueError,
        "Cannot convert object of length %d in to a %d byte array",
        actualsize,
        size );
    return -1;
}
コード例 #6
0
ファイル: pylogcount.c プロジェクト: waterson/pylogcount
/* Adds each of the arguments to the logcount. */
static int
add(LogCount *self, PyObject *args)
{
  Py_ssize_t i, n = PyTuple_Size(args);
  for (i = 0; i < n; ++i) {
    PyObject *arg = PyTuple_GetItem(args, i);
    char *buf;
    Py_ssize_t len;

    if (PyString_Check(arg)) {
      if (PyString_AsStringAndSize(arg, &buf, &len) < 0)
        return -1;

      logcount_add(&self->lc, (unsigned char *) buf, len);
    }
    else if (PyUnicode_Check(arg)) {
      buf = (char *) PyUnicode_AS_DATA(arg);
      len = PyUnicode_GET_DATA_SIZE(arg);
      logcount_add(&self->lc, (unsigned char *) buf, len);
    }
    else {
      PyObject *str = PyObject_Str(arg);
      if (!str)
        return -1;

      if (PyString_AsStringAndSize(str, &buf, &len) < 0) {
        Py_DECREF(str);
        return -1;
      }

      logcount_add(&self->lc, (unsigned char *) buf, len);
      Py_DECREF(str);
    }
  }

  return 0;
}
コード例 #7
0
ファイル: common.c プロジェクト: JStech/numpy
NPY_NO_EXPORT int
PyArray_DTypeFromObjectHelper(PyObject *obj, int maxdims,
                              PyArray_Descr **out_dtype, int string_type)
{
    int i, size;
    PyArray_Descr *dtype = NULL;
    PyObject *ip;
    Py_buffer buffer_view;

    /* Check if it's an ndarray */
    if (PyArray_Check(obj)) {
        dtype = PyArray_DESCR((PyArrayObject *)obj);
        Py_INCREF(dtype);
        goto promote_types;
    }

    /* See if it's a python None */
    if (obj == Py_None) {
        dtype = PyArray_DescrFromType(NPY_OBJECT);
        if (dtype == NULL) {
            goto fail;
        }
        Py_INCREF(dtype);
        goto promote_types;
    }
    /* Check if it's a NumPy scalar */
    else if (PyArray_IsScalar(obj, Generic)) {
        if (!string_type) {
            dtype = PyArray_DescrFromScalar(obj);
            if (dtype == NULL) {
                goto fail;
            }
        }
        else {
            int itemsize;
            PyObject *temp;

            if (string_type == NPY_STRING) {
                if ((temp = PyObject_Str(obj)) == NULL) {
                    return -1;
                }
#if defined(NPY_PY3K)
    #if PY_VERSION_HEX >= 0x03030000
                itemsize = PyUnicode_GetLength(temp);
    #else
                itemsize = PyUnicode_GET_SIZE(temp);
    #endif
#else
                itemsize = PyString_GET_SIZE(temp);
#endif
            }
            else if (string_type == NPY_UNICODE) {
#if defined(NPY_PY3K)
                if ((temp = PyObject_Str(obj)) == NULL) {
#else
                if ((temp = PyObject_Unicode(obj)) == NULL) {
#endif
                    return -1;
                }
                itemsize = PyUnicode_GET_DATA_SIZE(temp);
#ifndef Py_UNICODE_WIDE
                itemsize <<= 1;
#endif
            }
            else {
                goto fail;
            }
            Py_DECREF(temp);
            if (*out_dtype != NULL &&
                    (*out_dtype)->type_num == string_type &&
                    (*out_dtype)->elsize >= itemsize) {
                return 0;
            }
            dtype = PyArray_DescrNewFromType(string_type);
            if (dtype == NULL) {
                goto fail;
            }
            dtype->elsize = itemsize;
        }
        goto promote_types;
    }

    /* Check if it's a Python scalar */
    dtype = _array_find_python_scalar_type(obj);
    if (dtype != NULL) {
        if (string_type) {
            int itemsize;
            PyObject *temp;

            if (string_type == NPY_STRING) {
                if ((temp = PyObject_Str(obj)) == NULL) {
                    return -1;
                }
#if defined(NPY_PY3K)
    #if PY_VERSION_HEX >= 0x03030000
                itemsize = PyUnicode_GetLength(temp);
    #else
                itemsize = PyUnicode_GET_SIZE(temp);
    #endif
#else
                itemsize = PyString_GET_SIZE(temp);
#endif
            }
            else if (string_type == NPY_UNICODE) {
#if defined(NPY_PY3K)
                if ((temp = PyObject_Str(obj)) == NULL) {
#else
                if ((temp = PyObject_Unicode(obj)) == NULL) {
#endif
                    return -1;
                }
                itemsize = PyUnicode_GET_DATA_SIZE(temp);
#ifndef Py_UNICODE_WIDE
                itemsize <<= 1;
#endif
            }
            else {
                goto fail;
            }
            Py_DECREF(temp);
            if (*out_dtype != NULL &&
                    (*out_dtype)->type_num == string_type &&
                    (*out_dtype)->elsize >= itemsize) {
                return 0;
            }
            dtype = PyArray_DescrNewFromType(string_type);
            if (dtype == NULL) {
                goto fail;
            }
            dtype->elsize = itemsize;
        }
        goto promote_types;
    }

    /* Check if it's an ASCII string */
    if (PyBytes_Check(obj)) {
        int itemsize = PyString_GET_SIZE(obj);

        /* If it's already a big enough string, don't bother type promoting */
        if (*out_dtype != NULL &&
                        (*out_dtype)->type_num == NPY_STRING &&
                        (*out_dtype)->elsize >= itemsize) {
            return 0;
        }
        dtype = PyArray_DescrNewFromType(NPY_STRING);
        if (dtype == NULL) {
            goto fail;
        }
        dtype->elsize = itemsize;
        goto promote_types;
    }

    /* Check if it's a Unicode string */
    if (PyUnicode_Check(obj)) {
        int itemsize = PyUnicode_GET_DATA_SIZE(obj);
#ifndef Py_UNICODE_WIDE
        itemsize <<= 1;
#endif

        /*
         * If it's already a big enough unicode object,
         * don't bother type promoting
         */
        if (*out_dtype != NULL &&
                        (*out_dtype)->type_num == NPY_UNICODE &&
                        (*out_dtype)->elsize >= itemsize) {
            return 0;
        }
        dtype = PyArray_DescrNewFromType(NPY_UNICODE);
        if (dtype == NULL) {
            goto fail;
        }
        dtype->elsize = itemsize;
        goto promote_types;
    }

    /* PEP 3118 buffer interface */
    if (PyObject_CheckBuffer(obj) == 1) {
        memset(&buffer_view, 0, sizeof(Py_buffer));
        if (PyObject_GetBuffer(obj, &buffer_view,
                               PyBUF_FORMAT|PyBUF_STRIDES) == 0 ||
            PyObject_GetBuffer(obj, &buffer_view, PyBUF_FORMAT) == 0) {

            PyErr_Clear();
            dtype = _descriptor_from_pep3118_format(buffer_view.format);
            PyBuffer_Release(&buffer_view);
            if (dtype) {
                goto promote_types;
            }
        }
        else if (PyObject_GetBuffer(obj, &buffer_view, PyBUF_STRIDES) == 0 ||
                 PyObject_GetBuffer(obj, &buffer_view, PyBUF_SIMPLE) == 0) {

            PyErr_Clear();
            dtype = PyArray_DescrNewFromType(NPY_VOID);
            dtype->elsize = buffer_view.itemsize;
            PyBuffer_Release(&buffer_view);
            goto promote_types;
        }
        else {
            PyErr_Clear();
        }
    }

    /* The array interface */
    ip = PyArray_GetAttrString_SuppressException(obj, "__array_interface__");
    if (ip != NULL) {
        if (PyDict_Check(ip)) {
            PyObject *typestr;
#if defined(NPY_PY3K)
            PyObject *tmp = NULL;
#endif
            typestr = PyDict_GetItemString(ip, "typestr");
#if defined(NPY_PY3K)
            /* Allow unicode type strings */
            if (PyUnicode_Check(typestr)) {
                tmp = PyUnicode_AsASCIIString(typestr);
                typestr = tmp;
            }
#endif
            if (typestr && PyBytes_Check(typestr)) {
                dtype =_array_typedescr_fromstr(PyBytes_AS_STRING(typestr));
#if defined(NPY_PY3K)
                if (tmp == typestr) {
                    Py_DECREF(tmp);
                }
#endif
                Py_DECREF(ip);
                if (dtype == NULL) {
                    goto fail;
                }
                goto promote_types;
            }
        }
        Py_DECREF(ip);
    }

    /* The array struct interface */
    ip = PyArray_GetAttrString_SuppressException(obj, "__array_struct__");
    if (ip != NULL) {
        PyArrayInterface *inter;
        char buf[40];

        if (NpyCapsule_Check(ip)) {
            inter = (PyArrayInterface *)NpyCapsule_AsVoidPtr(ip);
            if (inter->two == 2) {
                PyOS_snprintf(buf, sizeof(buf),
                        "|%c%d", inter->typekind, inter->itemsize);
                dtype = _array_typedescr_fromstr(buf);
                Py_DECREF(ip);
                if (dtype == NULL) {
                    goto fail;
                }
                goto promote_types;
            }
        }
        Py_DECREF(ip);
    }

    /* The old buffer interface */
#if !defined(NPY_PY3K)
    if (PyBuffer_Check(obj)) {
        dtype = PyArray_DescrNewFromType(NPY_VOID);
        if (dtype == NULL) {
            goto fail;
        }
        dtype->elsize = Py_TYPE(obj)->tp_as_sequence->sq_length(obj);
        PyErr_Clear();
        goto promote_types;
    }
#endif

    /* The __array__ attribute */
    ip = PyArray_GetAttrString_SuppressException(obj, "__array__");
    if (ip != NULL) {
        Py_DECREF(ip);
        ip = PyObject_CallMethod(obj, "__array__", NULL);
        if(ip && PyArray_Check(ip)) {
            dtype = PyArray_DESCR((PyArrayObject *)ip);
            Py_INCREF(dtype);
            Py_DECREF(ip);
            goto promote_types;
        }
        Py_XDECREF(ip);
        if (PyErr_Occurred()) {
            goto fail;
        }
    }

    /* Not exactly sure what this is about... */
#if !defined(NPY_PY3K)
    if (PyInstance_Check(obj)) {
        dtype = _use_default_type(obj);
        if (dtype == NULL) {
            goto fail;
        }
        else {
            goto promote_types;
        }
    }
#endif

    /*
     * If we reached the maximum recursion depth without hitting one
     * of the above cases, the output dtype should be OBJECT
     */
    if (maxdims == 0 || !PySequence_Check(obj)) {
        if (*out_dtype == NULL || (*out_dtype)->type_num != NPY_OBJECT) {
            Py_XDECREF(*out_dtype);
            *out_dtype = PyArray_DescrFromType(NPY_OBJECT);
            if (*out_dtype == NULL) {
                return -1;
            }
        }
        return 0;
    }

    /* Recursive case */
    size = PySequence_Size(obj);
    if (size < 0) {
        goto fail;
    }
    /* Recursive call for each sequence item */
    for (i = 0; i < size; ++i) {
        int res;
        ip = PySequence_GetItem(obj, i);
        if (ip == NULL) {
            goto fail;
        }
        res = PyArray_DTypeFromObjectHelper(ip, maxdims - 1,
                                            out_dtype, string_type);
        if (res < 0) {
            Py_DECREF(ip);
            goto fail;
        }
        else if (res > 0) {
            Py_DECREF(ip);
            return res;
        }
        Py_DECREF(ip);
    }

    return 0;


promote_types:
    /* Set 'out_dtype' if it's NULL */
    if (*out_dtype == NULL) {
        if (!string_type && dtype->type_num == NPY_STRING) {
            Py_DECREF(dtype);
            return RETRY_WITH_STRING;
        }
        if (!string_type && dtype->type_num == NPY_UNICODE) {
            Py_DECREF(dtype);
            return RETRY_WITH_UNICODE;
        }
        *out_dtype = dtype;
        return 0;
    }
    /* Do type promotion with 'out_dtype' */
    else {
        PyArray_Descr *res_dtype = PyArray_PromoteTypes(dtype, *out_dtype);
        Py_DECREF(dtype);
        if (res_dtype == NULL) {
            return -1;
        }
        if (!string_type &&
                res_dtype->type_num == NPY_UNICODE &&
                (*out_dtype)->type_num != NPY_UNICODE) {
            Py_DECREF(res_dtype);
            return RETRY_WITH_UNICODE;
        }
        if (!string_type &&
                res_dtype->type_num == NPY_STRING &&
                (*out_dtype)->type_num != NPY_STRING) {
            Py_DECREF(res_dtype);
            return RETRY_WITH_STRING;
        }
        Py_DECREF(*out_dtype);
        *out_dtype = res_dtype;
        return 0;
    }

fail:
    Py_XDECREF(*out_dtype);
    *out_dtype = NULL;
    return -1;
}

#undef RETRY_WITH_STRING
#undef RETRY_WITH_UNICODE

/* new reference */
NPY_NO_EXPORT PyArray_Descr *
_array_typedescr_fromstr(char *c_str)
{
    PyArray_Descr *descr = NULL;
    PyObject *stringobj = PyString_FromString(c_str);

    if (stringobj == NULL) {
        return NULL;
    }
    if (PyArray_DescrConverter(stringobj, &descr) != NPY_SUCCEED) {
        Py_DECREF(stringobj);
        return NULL;
    }
    Py_DECREF(stringobj);
    return descr;
}


NPY_NO_EXPORT char *
index2ptr(PyArrayObject *mp, npy_intp i)
{
    npy_intp dim0;

    if (PyArray_NDIM(mp) == 0) {
        PyErr_SetString(PyExc_IndexError, "0-d arrays can't be indexed");
        return NULL;
    }
    dim0 = PyArray_DIMS(mp)[0];
    if (check_and_adjust_index(&i, dim0, 0) < 0)
        return NULL;
    if (i == 0) {
        return PyArray_DATA(mp);
    }
    return PyArray_BYTES(mp)+i*PyArray_STRIDES(mp)[0];
}
コード例 #8
0
// @pymethod |PySTGMEDIUM|set|Sets the type and data of the object.
PyObject *PySet(PyObject *self, PyObject *args)
{
	int tymed;
	PyObject *ob;
	// @pyparm int|tymed||The type of the data
	// @pyparm object|data||
	if (!PyArg_ParseTuple(args, "iO:set", &tymed, &ob))
		return NULL;

	PySTGMEDIUM *ps = (PySTGMEDIUM *)self;
	ps->Close(); // ensure any old data clean
	switch (tymed) {
		case TYMED_GDI:{
			HBITMAP htmp;
			if (!PyWinObject_AsHANDLE(ob, (HANDLE *)&htmp))
				return NULL;
			ps->medium.hBitmap = htmp;
			break;
			}
		case TYMED_MFPICT:{
			HMETAFILEPICT htmp;
			if (!PyWinObject_AsHANDLE(ob, (HANDLE *)&htmp))
				return NULL;
			ps->medium.hMetaFilePict = htmp;
			break;
			}
		case TYMED_ENHMF:{
			HENHMETAFILE htmp;
			if (!PyWinObject_AsHANDLE(ob, (HANDLE *)&htmp))
				return NULL;
			ps->medium.hEnhMetaFile = htmp;
			break;
			}
		case TYMED_HGLOBAL: {
			const void * buf = NULL;
			Py_ssize_t cb = 0;
			// In py3k, unicode objects don't support the buffer
			// protocol, so explicitly check string types first.
			// We need to include the NULL for strings and unicode, as the
			// Windows clipboard functions will assume it is there for
			// text related formats (eg, CF_TEXT).
			if (PyString_Check(ob)) {
				cb = PyString_GET_SIZE(ob) + 1; // for the NULL
				buf = (void *)PyString_AS_STRING(ob);
			} else if (PyUnicode_Check(ob)) {
				cb = PyUnicode_GET_DATA_SIZE(ob) + sizeof(Py_UNICODE);
				buf = (void *)PyUnicode_AS_UNICODE(ob);
			} else {
				if (PyObject_AsReadBuffer(ob,&buf,&cb)==-1) 
					return PyErr_Format(PyExc_TypeError, "tymed value of %d requires a string/unicode/buffer", tymed);
				// no extra nulls etc needed here.
			}
			ps->medium.hGlobal = GlobalAlloc(GMEM_FIXED, cb);
			if (!ps->medium.hGlobal)
				return PyErr_NoMemory();
			memcpy( (void *)ps->medium.hGlobal, buf, cb);
			break;
		}
		case TYMED_FILE: 
			if (!PyWinObject_AsTaskAllocatedWCHAR(ob, &ps->medium.lpszFileName, FALSE, NULL))
				return FALSE;
			break;
		case TYMED_ISTREAM:
			if (!PyCom_InterfaceFromPyInstanceOrObject(ob, IID_IStream, (void **)&ps->medium.pstm, FALSE/* bNoneOK */))
				return FALSE;
			break;
		case TYMED_ISTORAGE:
			if (!PyCom_InterfaceFromPyInstanceOrObject(ob, IID_IStorage, (void **)&ps->medium.pstg, FALSE/* bNoneOK */))
				return FALSE;
			break;
		default:
			PyErr_Format(PyExc_ValueError, "Unknown tymed value '%d'", tymed);
			return NULL;
	}
	ps->medium.tymed = tymed;
	Py_INCREF(Py_None);
	return Py_None;
}
コード例 #9
0
ファイル: TypeConversion.c プロジェクト: GIScarl/cython
static CYTHON_INLINE char* __Pyx_PyObject_AsStringAndSize(PyObject* o, Py_ssize_t *length) {
#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT
    if (
#if PY_MAJOR_VERSION < 3 && __PYX_DEFAULT_STRING_ENCODING_IS_ASCII
            __Pyx_sys_getdefaultencoding_not_ascii && 
#endif
            PyUnicode_Check(o)) {
#if PY_VERSION_HEX < 0x03030000
        char* defenc_c;
        // borrowed, cached reference
        PyObject* defenc = _PyUnicode_AsDefaultEncodedString(o, NULL);
        if (!defenc) return NULL;
        defenc_c = PyBytes_AS_STRING(defenc);
#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII
        {
            char* end = defenc_c + PyBytes_GET_SIZE(defenc);
            char* c;
            for (c = defenc_c; c < end; c++) {
                if ((unsigned char) (*c) >= 128) {
                    // raise the error
                    PyUnicode_AsASCIIString(o);
                    return NULL;
                }
            }
        }
#endif /*__PYX_DEFAULT_STRING_ENCODING_IS_ASCII*/
        *length = PyBytes_GET_SIZE(defenc);
        return defenc_c;
#else /* PY_VERSION_HEX < 0x03030000 */
        if (PyUnicode_READY(o) == -1) return NULL;
#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII
        if (PyUnicode_IS_ASCII(o)) {
            // cached for the lifetime of the object
            *length = PyUnicode_GET_DATA_SIZE(o);
            return PyUnicode_AsUTF8(o);
        } else {
            // raise the error
            PyUnicode_AsASCIIString(o);
            return NULL;
        }
#else /* __PYX_DEFAULT_STRING_ENCODING_IS_ASCII */
        return PyUnicode_AsUTF8AndSize(o, length);
#endif /* __PYX_DEFAULT_STRING_ENCODING_IS_ASCII */
#endif /* PY_VERSION_HEX < 0x03030000 */
    } else
#endif /* __PYX_DEFAULT_STRING_ENCODING_IS_ASCII  || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT */

#if PY_VERSION_HEX >= 0x02060000
    if (PyByteArray_Check(o)) {
        *length = PyByteArray_GET_SIZE(o);
        return PyByteArray_AS_STRING(o);
    } else
#endif
    {
        char* result;
        int r = PyBytes_AsStringAndSize(o, &result, length);
        if (unlikely(r < 0)) {
            return NULL;
        } else {
            return result;
        }
    }
}
コード例 #10
0
ファイル: common.c プロジェクト: BranYang/numpy
NPY_NO_EXPORT int
PyArray_DTypeFromObjectHelper(PyObject *obj, int maxdims,
                              PyArray_Descr **out_dtype, int string_type)
{
    int i, size;
    PyArray_Descr *dtype = NULL;
    PyObject *ip;
    Py_buffer buffer_view;
    /* types for sequence handling */
    PyObject ** objects;
    PyObject * seq;
    PyTypeObject * common_type;

    /* Check if it's an ndarray */
    if (PyArray_Check(obj)) {
        dtype = PyArray_DESCR((PyArrayObject *)obj);
        Py_INCREF(dtype);
        goto promote_types;
    }

    /* See if it's a python None */
    if (obj == Py_None) {
        dtype = PyArray_DescrFromType(NPY_OBJECT);
        if (dtype == NULL) {
            goto fail;
        }
        Py_INCREF(dtype);
        goto promote_types;
    }
    /* Check if it's a NumPy scalar */
    else if (PyArray_IsScalar(obj, Generic)) {
        if (!string_type) {
            dtype = PyArray_DescrFromScalar(obj);
            if (dtype == NULL) {
                goto fail;
            }
        }
        else {
            int itemsize;
            PyObject *temp;

            if (string_type == NPY_STRING) {
                if ((temp = PyObject_Str(obj)) == NULL) {
                    return -1;
                }
#if defined(NPY_PY3K)
    #if PY_VERSION_HEX >= 0x03030000
                itemsize = PyUnicode_GetLength(temp);
    #else
                itemsize = PyUnicode_GET_SIZE(temp);
    #endif
#else
                itemsize = PyString_GET_SIZE(temp);
#endif
            }
            else if (string_type == NPY_UNICODE) {
#if defined(NPY_PY3K)
                if ((temp = PyObject_Str(obj)) == NULL) {
#else
                if ((temp = PyObject_Unicode(obj)) == NULL) {
#endif
                    return -1;
                }
                itemsize = PyUnicode_GET_DATA_SIZE(temp);
#ifndef Py_UNICODE_WIDE
                itemsize <<= 1;
#endif
            }
            else {
                goto fail;
            }
            Py_DECREF(temp);
            if (*out_dtype != NULL &&
                    (*out_dtype)->type_num == string_type &&
                    (*out_dtype)->elsize >= itemsize) {
                return 0;
            }
            dtype = PyArray_DescrNewFromType(string_type);
            if (dtype == NULL) {
                goto fail;
            }
            dtype->elsize = itemsize;
        }
        goto promote_types;
    }

    /* Check if it's a Python scalar */
    dtype = _array_find_python_scalar_type(obj);
    if (dtype != NULL) {
        if (string_type) {
            int itemsize;
            PyObject *temp;

            if (string_type == NPY_STRING) {
                if ((temp = PyObject_Str(obj)) == NULL) {
                    return -1;
                }
#if defined(NPY_PY3K)
    #if PY_VERSION_HEX >= 0x03030000
                itemsize = PyUnicode_GetLength(temp);
    #else
                itemsize = PyUnicode_GET_SIZE(temp);
    #endif
#else
                itemsize = PyString_GET_SIZE(temp);
#endif
            }
            else if (string_type == NPY_UNICODE) {
#if defined(NPY_PY3K)
                if ((temp = PyObject_Str(obj)) == NULL) {
#else
                if ((temp = PyObject_Unicode(obj)) == NULL) {
#endif
                    return -1;
                }
                itemsize = PyUnicode_GET_DATA_SIZE(temp);
#ifndef Py_UNICODE_WIDE
                itemsize <<= 1;
#endif
            }
            else {
                goto fail;
            }
            Py_DECREF(temp);
            if (*out_dtype != NULL &&
                    (*out_dtype)->type_num == string_type &&
                    (*out_dtype)->elsize >= itemsize) {
                return 0;
            }
            dtype = PyArray_DescrNewFromType(string_type);
            if (dtype == NULL) {
                goto fail;
            }
            dtype->elsize = itemsize;
        }
        goto promote_types;
    }

    /* Check if it's an ASCII string */
    if (PyBytes_Check(obj)) {
        int itemsize = PyString_GET_SIZE(obj);

        /* If it's already a big enough string, don't bother type promoting */
        if (*out_dtype != NULL &&
                        (*out_dtype)->type_num == NPY_STRING &&
                        (*out_dtype)->elsize >= itemsize) {
            return 0;
        }
        dtype = PyArray_DescrNewFromType(NPY_STRING);
        if (dtype == NULL) {
            goto fail;
        }
        dtype->elsize = itemsize;
        goto promote_types;
    }

    /* Check if it's a Unicode string */
    if (PyUnicode_Check(obj)) {
        int itemsize = PyUnicode_GET_DATA_SIZE(obj);
#ifndef Py_UNICODE_WIDE
        itemsize <<= 1;
#endif

        /*
         * If it's already a big enough unicode object,
         * don't bother type promoting
         */
        if (*out_dtype != NULL &&
                        (*out_dtype)->type_num == NPY_UNICODE &&
                        (*out_dtype)->elsize >= itemsize) {
            return 0;
        }
        dtype = PyArray_DescrNewFromType(NPY_UNICODE);
        if (dtype == NULL) {
            goto fail;
        }
        dtype->elsize = itemsize;
        goto promote_types;
    }

    /* PEP 3118 buffer interface */
    if (PyObject_CheckBuffer(obj) == 1) {
        memset(&buffer_view, 0, sizeof(Py_buffer));
        if (PyObject_GetBuffer(obj, &buffer_view,
                               PyBUF_FORMAT|PyBUF_STRIDES) == 0 ||
            PyObject_GetBuffer(obj, &buffer_view, PyBUF_FORMAT) == 0) {

            PyErr_Clear();
            dtype = _descriptor_from_pep3118_format(buffer_view.format);
            PyBuffer_Release(&buffer_view);
            if (dtype) {
                goto promote_types;
            }
        }
        else if (PyObject_GetBuffer(obj, &buffer_view, PyBUF_STRIDES) == 0 ||
                 PyObject_GetBuffer(obj, &buffer_view, PyBUF_SIMPLE) == 0) {

            PyErr_Clear();
            dtype = PyArray_DescrNewFromType(NPY_VOID);
            dtype->elsize = buffer_view.itemsize;
            PyBuffer_Release(&buffer_view);
            goto promote_types;
        }
        else {
            PyErr_Clear();
        }
    }

    /* The array interface */
    ip = PyArray_LookupSpecial_OnInstance(obj, "__array_interface__");
    if (ip != NULL) {
        if (PyDict_Check(ip)) {
            PyObject *typestr;
#if defined(NPY_PY3K)
            PyObject *tmp = NULL;
#endif
            typestr = PyDict_GetItemString(ip, "typestr");
#if defined(NPY_PY3K)
            /* Allow unicode type strings */
            if (PyUnicode_Check(typestr)) {
                tmp = PyUnicode_AsASCIIString(typestr);
                typestr = tmp;
            }
#endif
            if (typestr && PyBytes_Check(typestr)) {
                dtype =_array_typedescr_fromstr(PyBytes_AS_STRING(typestr));
#if defined(NPY_PY3K)
                if (tmp == typestr) {
                    Py_DECREF(tmp);
                }
#endif
                Py_DECREF(ip);
                if (dtype == NULL) {
                    goto fail;
                }
                goto promote_types;
            }
        }
        Py_DECREF(ip);
    }

    /* The array struct interface */
    ip = PyArray_LookupSpecial_OnInstance(obj, "__array_struct__");
    if (ip != NULL) {
        PyArrayInterface *inter;
        char buf[40];

        if (NpyCapsule_Check(ip)) {
            inter = (PyArrayInterface *)NpyCapsule_AsVoidPtr(ip);
            if (inter->two == 2) {
                PyOS_snprintf(buf, sizeof(buf),
                        "|%c%d", inter->typekind, inter->itemsize);
                dtype = _array_typedescr_fromstr(buf);
                Py_DECREF(ip);
                if (dtype == NULL) {
                    goto fail;
                }
                goto promote_types;
            }
        }
        Py_DECREF(ip);
    }

    /* The old buffer interface */
#if !defined(NPY_PY3K)
    if (PyBuffer_Check(obj)) {
        dtype = PyArray_DescrNewFromType(NPY_VOID);
        if (dtype == NULL) {
            goto fail;
        }
        dtype->elsize = Py_TYPE(obj)->tp_as_sequence->sq_length(obj);
        PyErr_Clear();
        goto promote_types;
    }
#endif

    /* The __array__ attribute */
    ip = PyArray_LookupSpecial_OnInstance(obj, "__array__");
    if (ip != NULL) {
        Py_DECREF(ip);
        ip = PyObject_CallMethod(obj, "__array__", NULL);
        if(ip && PyArray_Check(ip)) {
            dtype = PyArray_DESCR((PyArrayObject *)ip);
            Py_INCREF(dtype);
            Py_DECREF(ip);
            goto promote_types;
        }
        Py_XDECREF(ip);
        if (PyErr_Occurred()) {
            goto fail;
        }
    }

    /*
     * If we reached the maximum recursion depth without hitting one
     * of the above cases, and obj isn't a sequence-like object, the output
     * dtype should be either OBJECT or a user-defined type.
     *
     * Note that some libraries define sequence-like classes but want them to
     * be treated as objects, and they expect numpy to treat it as an object if
     * __len__ is not defined.
     */
    if (maxdims == 0 || !PySequence_Check(obj) || PySequence_Size(obj) < 0) {
        // clear any PySequence_Size error, which corrupts further calls to it
        PyErr_Clear();

        if (*out_dtype == NULL || (*out_dtype)->type_num != NPY_OBJECT) {
            Py_XDECREF(*out_dtype);
            *out_dtype = PyArray_DescrFromType(NPY_OBJECT);
            if (*out_dtype == NULL) {
                return -1;
            }
        }
        return 0;
    }

    /* Recursive case, first check the sequence contains only one type */
    seq = PySequence_Fast(obj, "Could not convert object to sequence");
    if (seq == NULL) {
        goto fail;
    }
    size = PySequence_Fast_GET_SIZE(seq);
    objects = PySequence_Fast_ITEMS(seq);
    common_type = size > 0 ? Py_TYPE(objects[0]) : NULL;
    for (i = 1; i < size; ++i) {
        if (Py_TYPE(objects[i]) != common_type) {
            common_type = NULL;
            break;
        }
    }

    /* all types are the same and scalar, one recursive call is enough */
    if (common_type != NULL && !string_type &&
            (common_type == &PyFloat_Type ||
/* TODO: we could add longs if we add a range check */
#if !defined(NPY_PY3K)
             common_type == &PyInt_Type ||
#endif
             common_type == &PyBool_Type ||
             common_type == &PyComplex_Type)) {
        size = 1;
    }

    /* Recursive call for each sequence item */
    for (i = 0; i < size; ++i) {
        int res = PyArray_DTypeFromObjectHelper(objects[i], maxdims - 1,
                                                out_dtype, string_type);
        if (res < 0) {
            Py_DECREF(seq);
            goto fail;
        }
        else if (res > 0) {
            Py_DECREF(seq);
            return res;
        }
    }

    Py_DECREF(seq);

    return 0;


promote_types:
    /* Set 'out_dtype' if it's NULL */
    if (*out_dtype == NULL) {
        if (!string_type && dtype->type_num == NPY_STRING) {
            Py_DECREF(dtype);
            return RETRY_WITH_STRING;
        }
        if (!string_type && dtype->type_num == NPY_UNICODE) {
            Py_DECREF(dtype);
            return RETRY_WITH_UNICODE;
        }
        *out_dtype = dtype;
        return 0;
    }
    /* Do type promotion with 'out_dtype' */
    else {
        PyArray_Descr *res_dtype = PyArray_PromoteTypes(dtype, *out_dtype);
        Py_DECREF(dtype);
        if (res_dtype == NULL) {
            return -1;
        }
        if (!string_type &&
                res_dtype->type_num == NPY_UNICODE &&
                (*out_dtype)->type_num != NPY_UNICODE) {
            Py_DECREF(res_dtype);
            return RETRY_WITH_UNICODE;
        }
        if (!string_type &&
                res_dtype->type_num == NPY_STRING &&
                (*out_dtype)->type_num != NPY_STRING) {
            Py_DECREF(res_dtype);
            return RETRY_WITH_STRING;
        }
        Py_DECREF(*out_dtype);
        *out_dtype = res_dtype;
        return 0;
    }

fail:
    Py_XDECREF(*out_dtype);
    *out_dtype = NULL;
    return -1;
}

#undef RETRY_WITH_STRING
#undef RETRY_WITH_UNICODE

/* new reference */
NPY_NO_EXPORT PyArray_Descr *
_array_typedescr_fromstr(char *c_str)
{
    PyArray_Descr *descr = NULL;
    PyObject *stringobj = PyString_FromString(c_str);

    if (stringobj == NULL) {
        return NULL;
    }
    if (PyArray_DescrConverter(stringobj, &descr) != NPY_SUCCEED) {
        Py_DECREF(stringobj);
        return NULL;
    }
    Py_DECREF(stringobj);
    return descr;
}


NPY_NO_EXPORT char *
index2ptr(PyArrayObject *mp, npy_intp i)
{
    npy_intp dim0;

    if (PyArray_NDIM(mp) == 0) {
        PyErr_SetString(PyExc_IndexError, "0-d arrays can't be indexed");
        return NULL;
    }
    dim0 = PyArray_DIMS(mp)[0];
    if (check_and_adjust_index(&i, dim0, 0, NULL) < 0)
        return NULL;
    if (i == 0) {
        return PyArray_DATA(mp);
    }
    return PyArray_BYTES(mp)+i*PyArray_STRIDES(mp)[0];
}
コード例 #11
0
/**
 * Evaluate the code and return the value
 * @return
 */
QVariant PythonScript::evaluateImpl() {
  ScopedPythonGIL lock;
  PyObject *compiledCode = this->compileToByteCode(true);
  if (!compiledCode) {
    return QVariant("");
  }
  PyObject *pyret;
  beginStdoutRedirect();
  if (PyCallable_Check(compiledCode)) {
    PyObject *empty_tuple = PyTuple_New(0);
    pyret = PyObject_Call(compiledCode, empty_tuple, localDict);
    Py_DECREF(empty_tuple);
  } else {
    pyret = PyEval_EvalCode(CODE_OBJECT(compiledCode), localDict, localDict);
  }
  endStdoutRedirect();
  if (!pyret) {
    if (PyErr_ExceptionMatches(PyExc_ValueError) ||
        PyErr_ExceptionMatches(PyExc_ZeroDivisionError)) {
      PyErr_Clear(); // silently ignore errors
      return QVariant("");
    } else {
      emit_error();
      return QVariant();
    }
  }

  QVariant qret = QVariant();
  /* None */
  if (pyret == Py_None) {
    qret = QVariant("");
  }
  /* numeric types */
  else if (PyFloat_Check(pyret)) {
    qret = QVariant(PyFloat_AS_DOUBLE(pyret));
  } else if (INT_CHECK(pyret)) {
    qret = QVariant((qlonglong)TO_LONG(pyret));
  }
#if !defined(IS_PY3K)
  else if (PyLong_Check(pyret)) {
    qret = QVariant((qlonglong)PyLong_AsLongLong(pyret));
  }
#endif
  else if (PyNumber_Check(pyret)) {
    PyObject *number = PyNumber_Float(pyret);
    if (number) {
      qret = QVariant(PyFloat_AS_DOUBLE(number));
      Py_DECREF(number);
    }
  }
  /* bool */
  else if (PyBool_Check(pyret)) {
    qret = QVariant(pyret == Py_True);
  }
  // could handle advanced types (such as PyList->QValueList) here if needed
  /* fallback: try to convert to (unicode) string */
  if (!qret.isValid()) {
#if defined(IS_PY3K)
    // In 3 everything is unicode
    PyObject *pystring = PyObject_Str(pyret);
    if (pystring) {
      qret = QVariant(QString::fromUtf8(_PyUnicode_AsString(pystring)));
    }
#else
    PyObject *pystring = PyObject_Unicode(pyret);
    if (pystring) {
      PyObject *asUTF8 =
          PyUnicode_EncodeUTF8(PyUnicode_AS_UNICODE(pystring),
                               (int)PyUnicode_GET_DATA_SIZE(pystring), nullptr);
      Py_DECREF(pystring);
      if (asUTF8) {
        qret = QVariant(QString::fromUtf8(PyString_AS_STRING(asUTF8)));
        Py_DECREF(asUTF8);
      } else if ((pystring = PyObject_Str(pyret))) {
        qret = QVariant(QString(PyString_AS_STRING(pystring)));
        Py_DECREF(pystring);
      }
    }
#endif
  }
  Py_DECREF(pyret);
  if (PyErr_Occurred()) {
    if (PyErr_ExceptionMatches(PyExc_ValueError) ||
        PyErr_ExceptionMatches(PyExc_ZeroDivisionError)) {
      PyErr_Clear(); // silently ignore errors
      return QVariant("");
    } else {
      emit_error();
    }
    return QVariant();
  }
  return qret;
}
コード例 #12
0
QVariant PythonScript::eval()
{
    if (!isFunction) compiled = notCompiled;
    if (compiled != isCompiled && !compile(true))
        return QVariant();

    PyObject *pyret;
    beginStdoutRedirect();
    if (PyCallable_Check(PyCode)) {
        PyObject *empty_tuple = PyTuple_New(0);
        pyret = PyObject_Call(PyCode, empty_tuple, localDict);
        Py_DECREF(empty_tuple);
    } else
        pyret = PyEval_EvalCode((PyCodeObject*)PyCode, env()->globalDict(), localDict);
    endStdoutRedirect();
    if (!pyret) {
        if (PyErr_ExceptionMatches(PyExc_ValueError) ||
                PyErr_ExceptionMatches(PyExc_ZeroDivisionError)) {
            PyErr_Clear(); // silently ignore errors
            return  QVariant("");
        } else {
            emit_error(env()->errorMsg(), 0);
            return QVariant();
        }
    }

    QVariant qret = QVariant();
    /* None */
    if (pyret == Py_None)
        qret = QVariant("");
    /* numeric types */
    else if (PyFloat_Check(pyret))
        qret = QVariant(PyFloat_AS_DOUBLE(pyret));
    else if (PyInt_Check(pyret))
        qret = QVariant((qlonglong)PyInt_AS_LONG(pyret));
    else if (PyLong_Check(pyret))
        qret = QVariant((qlonglong)PyLong_AsLongLong(pyret));
    else if (PyNumber_Check(pyret)) {
        PyObject *number = PyNumber_Float(pyret);
        if (number) {
            qret = QVariant(PyFloat_AS_DOUBLE(number));
            Py_DECREF(number);
        }
        /* bool */
    } else if (PyBool_Check(pyret))
        qret = QVariant(pyret==Py_True, 0);
    // could handle advanced types (such as PyList->QValueList) here if needed
    /* fallback: try to convert to (unicode) string */
    if(!qret.isValid()) {
        PyObject *pystring = PyObject_Unicode(pyret);
        if (pystring) {
            PyObject *asUTF8 = PyUnicode_EncodeUTF8(PyUnicode_AS_UNICODE(pystring), PyUnicode_GET_DATA_SIZE(pystring), 0);
            Py_DECREF(pystring);
            if (asUTF8) {
                qret = QVariant(QString::fromUtf8(PyString_AS_STRING(asUTF8)));
                Py_DECREF(asUTF8);
            } else if (pystring = PyObject_Str(pyret)) {
                qret = QVariant(QString(PyString_AS_STRING(pystring)));
                Py_DECREF(pystring);
            }
        }
    }

    Py_DECREF(pyret);
    if (PyErr_Occurred()) {
        if (PyErr_ExceptionMatches(PyExc_ValueError) ||
                PyErr_ExceptionMatches(PyExc_ZeroDivisionError)) {
            PyErr_Clear(); // silently ignore errors
            return  QVariant("");
        } else {
            emit_error(env()->errorMsg(), 0);
            return QVariant();
        }
    } else
        return qret;
}
コード例 #13
0
ファイル: libgrowl.c プロジェクト: Dieterbe/dvcs-autosync
static PyObject * growl_PostDictionary(CFStringRef name, PyObject *self, PyObject *args) {
	int i, j;

	PyObject *inputDict;
	PyObject *pKeys = NULL;
	PyObject *pKey, *pValue;

	CFMutableDictionaryRef note = CFDictionaryCreateMutable(kCFAllocatorDefault,
															/*capacity*/ 0,
															&kCFTypeDictionaryKeyCallBacks,
															&kCFTypeDictionaryValueCallBacks);

	if (!PyArg_ParseTuple(args, "O!", &PyDict_Type, &inputDict))
		goto error;

	pKeys = PyDict_Keys(inputDict);
	for (i = 0; i < PyList_Size(pKeys); ++i) {
		CFStringRef convertedKey;

		/* Converting the PyDict key to NSString and used for key in note */
		pKey = PyList_GetItem(pKeys, i);
		if (!pKey)
			// Exception already set
			goto error;
		pValue = PyDict_GetItem(inputDict, pKey);
		if (!pValue) {
			// XXX Neeed a real Error message here.
			PyErr_SetString(PyExc_TypeError," ");
			goto error;
		}
		if (PyUnicode_Check(pKey)) {
			convertedKey = CFStringCreateWithBytes(kCFAllocatorDefault,
												   (const UInt8 *)PyUnicode_AS_DATA(pKey),
												   PyUnicode_GET_DATA_SIZE(pKey),
												   kCFStringEncodingUnicode,
												   false);
		} else if (PyString_Check(pKey)) {
			convertedKey = CFStringCreateWithCString(kCFAllocatorDefault,
													 PyString_AsString(pKey),
													 kCFStringEncodingUTF8);
		} else {
			PyErr_SetString(PyExc_TypeError,"The Dict keys must be strings/unicode");
			goto error;
		}

		/* Converting the PyDict value to NSString or NSData based on class  */
		if (PyString_Check(pValue)) {
			CFStringRef convertedValue = CFStringCreateWithCString(kCFAllocatorDefault,
																   PyString_AS_STRING(pValue),
																   kCFStringEncodingUTF8);
			CFDictionarySetValue(note, convertedKey, convertedValue);
			CFRelease(convertedValue);
		} else if (PyUnicode_Check(pValue)) {
			CFStringRef convertedValue = CFStringCreateWithBytes(kCFAllocatorDefault,
																 (const UInt8 *)PyUnicode_AS_DATA(pValue),
																 PyUnicode_GET_DATA_SIZE(pValue),
																 kCFStringEncodingUnicode,
																 false);
			CFDictionarySetValue(note, convertedKey, convertedValue);
			CFRelease(convertedValue);
		} else if (PyInt_Check(pValue)) {
			long v = PyInt_AS_LONG(pValue);
			CFNumberRef convertedValue = CFNumberCreate(kCFAllocatorDefault,
														kCFNumberLongType,
														&v);
			CFDictionarySetValue(note, convertedKey, convertedValue);
			CFRelease(convertedValue);
		} else if (pValue == Py_None) {
			CFDataRef convertedValue = CFDataCreate(kCFAllocatorDefault, NULL, 0);
			CFDictionarySetValue(note, convertedKey, convertedValue);
			CFRelease(convertedValue);
		} else if (PyList_Check(pValue)) {
			int size = PyList_Size(pValue);
			CFMutableArrayRef listHolder = CFArrayCreateMutable(kCFAllocatorDefault,
																size,
																&kCFTypeArrayCallBacks);
			for (j = 0; j < size; ++j) {
				PyObject *lValue = PyList_GetItem(pValue, j);
				if (PyString_Check(lValue)) {
					CFStringRef convertedValue = CFStringCreateWithCString(kCFAllocatorDefault,
																		   PyString_AS_STRING(lValue),
																		   kCFStringEncodingUTF8);
					CFArrayAppendValue(listHolder, convertedValue);
					CFRelease(convertedValue);
				} else if (PyUnicode_Check(lValue)) {
					CFStringRef convertedValue = CFStringCreateWithBytes(kCFAllocatorDefault,
																		 (const UInt8 *)PyUnicode_AS_DATA(lValue),
																		 PyUnicode_GET_DATA_SIZE(lValue),
																		 kCFStringEncodingUnicode,
																		 false);
					CFArrayAppendValue(listHolder, convertedValue);
					CFRelease(convertedValue);
				} else {
					CFRelease(convertedKey);
					PyErr_SetString(PyExc_TypeError,"The lists must only contain strings");
					goto error;
				}
			}
			CFDictionarySetValue(note, convertedKey, listHolder);
			CFRelease(listHolder);
		} else if (PyObject_HasAttrString(pValue, "rawImageData")) {
			PyObject *lValue = PyObject_GetAttrString(pValue, "rawImageData");
			if (!lValue) {
				goto error;
			} else if (PyString_Check(lValue)) {
				CFDataRef convertedValue = CFDataCreate(kCFAllocatorDefault,
														(const UInt8 *)PyString_AsString(lValue),
														PyString_Size(lValue));
				CFDictionarySetValue(note, convertedKey, convertedValue);
				CFRelease(convertedValue);
			} else {
				CFRelease(convertedKey);
				PyErr_SetString(PyExc_TypeError, "Icon with rawImageData attribute present must ensure it is a string.");
				goto error;
			}
		} else {
			CFRelease(convertedKey);
			PyErr_SetString(PyExc_TypeError, "Value is not of Str/List");
			goto error;
		}
		CFRelease(convertedKey);
	}

	Py_BEGIN_ALLOW_THREADS
	CFNotificationCenterPostNotification(CFNotificationCenterGetDistributedCenter(),
										 /*name*/ name,
										 /*object*/ NULL,
										 /*userInfo*/ note,
										 /*deliverImmediately*/ false);
	CFRelease(note);
	Py_END_ALLOW_THREADS

	Py_DECREF(pKeys);

	Py_INCREF(Py_None);
	return Py_None;

error:
	CFRelease(note);

	Py_XDECREF(pKeys);

	return NULL;
}
コード例 #14
0
static PyObject *
py_set_clipboard_data(PyObject* self, PyObject* args)
{

	// @pyparm int|format||Specifies a clipboard format. For a description of
	//	the standard clipboard formats, see Standard Clipboard Formats.
	// @pyparm int/buffer|hMem||Integer handle to the data in the specified
	//	format, or string, unicode, or any object that supports the buffer interface.
	//	A global memory object is allocated, and the object's buffer is copied to the new memory.
	// This parameter can be 0, indicating that the window provides data in
	// the specified clipboard format (renders the format) upon request. If a
	// window delays rendering, it must process the WM_RENDERFORMAT and
	// WM_RENDERALLFORMATS messages.<nl>
	// After SetClipboardData is called, the system owns the object identified
	// by the hMem parameter. The application can read the data, but must not
	// free the handle or leave it locked. If the hMem parameter identifies a
	// memory object, the object must have been allocated using the GlobalAlloc
	// function with the GMEM_MOVEABLE and GMEM_DDESHARE flags. 
	int format;
	HANDLE handle;
	PyObject *obhandle;

	if (!PyArg_ParseTuple(args, "iO:SetClipboardData",
		&format, &obhandle))
		return NULL;
	if (!PyWinObject_AsHANDLE(obhandle , &handle)){
		PyErr_Clear();

		const void * buf = NULL;
		Py_ssize_t bufSize = 0;
		// In py3k, unicode no longer supports buffer interface
		if (PyUnicode_Check(obhandle)){
			bufSize = PyUnicode_GET_DATA_SIZE(obhandle) + sizeof(Py_UNICODE);
			buf=(void *)PyUnicode_AS_UNICODE(obhandle);
		} else {
			if (PyObject_AsReadBuffer(obhandle,&buf,&bufSize)==-1)
				return NULL;
			if (PyString_Check(obhandle))
				bufSize++;	// size doesnt include nulls!
			// else assume buffer needs no terminator...
		}
		handle = GlobalAlloc(GHND, bufSize);
		if (handle == NULL) {
			return ReturnAPIError("GlobalAlloc");
		}
		void *dest = GlobalLock(handle);
		memcpy(dest, buf, bufSize);
		GlobalUnlock(handle);
	}
	HANDLE data;
	Py_BEGIN_ALLOW_THREADS;
	data = SetClipboardData((UINT)format, handle);
	Py_END_ALLOW_THREADS;

	if (!data)
		// XXX - should we GlobalFree the mem?
		return ReturnAPIError("SetClipboardData");
	return PyWinLong_FromHANDLE(data);

	// @comm The uFormat parameter can identify a registered clipboard format,
	// or it can be one of the standard clipboard formats. For more information,
	// see Registered Clipboard Formats and Standard Clipboard Formats.<nl>
	// The system performs implicit data format conversions between certain
	// clipboard formats when an application calls the GetClipboardData function.
	// For example, if the CF_OEMTEXT format is on the clipboard, a window can
	// retrieve data in the CF_TEXT format. The format on the clipboard is
	// converted to the requested format on demand. For more information, see
	// Synthesized Clipboard Formats. 

	// @pyseeapi SetClipboardData

	// @rdesc If the function succeeds, the return value is integer handle
	// of the data.<nl>
	// If the function fails, win32api.error is raised with the GetLastError
	// info.
}
コード例 #15
0
ファイル: common.c プロジェクト: balarsen/numpy
/*
 * Recursively examines the object to determine an appropriate dtype
 * to use for converting to an ndarray.
 *
 * 'obj' is the object to be converted to an ndarray.
 *
 * 'maxdims' is the maximum recursion depth.
 *
 * 'out_contains_na' gets set to 1 if an np.NA object is encountered.
 * The NA does not affect the dtype produced, so if this is set to 1
 * and the result is for an array without NA support, the dtype should
 * be switched to NPY_OBJECT. When adding multi-NA support, this should
 * also signal whether just regular NAs or NAs with payloads were seen.
 *
 * 'out_dtype' should be either NULL or a minimal starting dtype when
 * the function is called. It is updated with the results of type
 * promotion. This dtype does not get updated when processing NA objects.
 * This is reset to NULL on failure.
 *
 * Returns 0 on success, -1 on failure.
 */
NPY_NO_EXPORT int
PyArray_DTypeFromObject(PyObject *obj, int maxdims, int *out_contains_na,
                        PyArray_Descr **out_dtype)
{
    int i, size;
    PyArray_Descr *dtype = NULL;
    PyObject *ip;
#if PY_VERSION_HEX >= 0x02060000
    Py_buffer buffer_view;
#endif

    /* Check if it's an ndarray */
    if (PyArray_Check(obj)) {
        /* Check for any NAs in the array */
        int containsna = PyArray_ContainsNA((PyArrayObject *)obj, NULL, NULL);
        if (containsna == -1) {
            goto fail;
        }
        else if (containsna) {
            *out_contains_na = 1;
        }
        dtype = PyArray_DESCR((PyArrayObject *)obj);
        Py_INCREF(dtype);
        goto promote_types;
    }

    /* Check if it's a NumPy scalar */
    if (PyArray_IsScalar(obj, Generic)) {
        dtype = PyArray_DescrFromScalar(obj);
        if (dtype == NULL) {
            goto fail;
        }
        goto promote_types;
    }

    /* Check if it's a Python scalar */
    dtype = _array_find_python_scalar_type(obj);
    if (dtype != NULL) {
        goto promote_types;
    }

    /* Check if it's an NA */
    if (NpyNA_Check(obj)) {
        *out_contains_na = 1;
        return 0;
    }

    /* Check if it's an ASCII string */
    if (PyBytes_Check(obj)) {
        int itemsize = PyString_GET_SIZE(obj);

        /* If it's already a big enough string, don't bother type promoting */
        if (*out_dtype != NULL &&
                        (*out_dtype)->type_num == NPY_STRING &&
                        (*out_dtype)->elsize >= itemsize) {
            return 0;
        }
        dtype = PyArray_DescrNewFromType(NPY_STRING);
        if (dtype == NULL) {
            goto fail;
        }
        dtype->elsize = itemsize;
        goto promote_types;
    }

    /* Check if it's a Unicode string */
    if (PyUnicode_Check(obj)) {
        int itemsize = PyUnicode_GET_DATA_SIZE(obj);
#ifndef Py_UNICODE_WIDE
        itemsize <<= 1;
#endif

        /*
         * If it's already a big enough unicode object,
         * don't bother type promoting
         */
        if (*out_dtype != NULL &&
                        (*out_dtype)->type_num == NPY_UNICODE &&
                        (*out_dtype)->elsize >= itemsize) {
            return 0;
        }
        dtype = PyArray_DescrNewFromType(NPY_UNICODE);
        if (dtype == NULL) {
            goto fail;
        }
        dtype->elsize = itemsize;
        goto promote_types;
    }

#if PY_VERSION_HEX >= 0x02060000
    /* PEP 3118 buffer interface */
    memset(&buffer_view, 0, sizeof(Py_buffer));
    if (PyObject_GetBuffer(obj, &buffer_view, PyBUF_FORMAT|PyBUF_STRIDES) == 0 ||
        PyObject_GetBuffer(obj, &buffer_view, PyBUF_FORMAT) == 0) {

        PyErr_Clear();
        dtype = _descriptor_from_pep3118_format(buffer_view.format);
        PyBuffer_Release(&buffer_view);
        if (dtype) {
            goto promote_types;
        }
    }
    else if (PyObject_GetBuffer(obj, &buffer_view, PyBUF_STRIDES) == 0 ||
             PyObject_GetBuffer(obj, &buffer_view, PyBUF_SIMPLE) == 0) {

        PyErr_Clear();
        dtype = PyArray_DescrNewFromType(NPY_VOID);
        dtype->elsize = buffer_view.itemsize;
        PyBuffer_Release(&buffer_view);
        goto promote_types;
    }
    else {
        PyErr_Clear();
    }
#endif

    /* The array interface */
    ip = PyObject_GetAttrString(obj, "__array_interface__");
    if (ip != NULL) {
        if (PyDict_Check(ip)) {
            PyObject *typestr;
            typestr = PyDict_GetItemString(ip, "typestr");
            if (typestr && PyString_Check(typestr)) {
                dtype =_array_typedescr_fromstr(PyString_AS_STRING(typestr));
                Py_DECREF(ip);
                if (dtype == NULL) {
                    goto fail;
                }
                goto promote_types;
            }
        }
        Py_DECREF(ip);
    }
    else {
        PyErr_Clear();
    }

    /* The array struct interface */
    ip = PyObject_GetAttrString(obj, "__array_struct__");
    if (ip != NULL) {
        PyArrayInterface *inter;
        char buf[40];

        if (NpyCapsule_Check(ip)) {
            inter = (PyArrayInterface *)NpyCapsule_AsVoidPtr(ip);
            if (inter->two == 2) {
                PyOS_snprintf(buf, sizeof(buf),
                        "|%c%d", inter->typekind, inter->itemsize);
                dtype = _array_typedescr_fromstr(buf);
                Py_DECREF(ip);
                if (dtype == NULL) {
                    goto fail;
                }
                goto promote_types;
            }
        }
        Py_DECREF(ip);
    }
    else {
        PyErr_Clear();
    }

    /* The old buffer interface */
#if !defined(NPY_PY3K)
    if (PyBuffer_Check(obj)) {
        dtype = PyArray_DescrNewFromType(NPY_VOID);
        if (dtype == NULL) {
            goto fail;
        }
        dtype->elsize = Py_TYPE(obj)->tp_as_sequence->sq_length(obj);
        PyErr_Clear();
        goto promote_types;
    }
#endif

    /* The __array__ attribute */
    if (PyObject_HasAttrString(obj, "__array__")) {
        ip = PyObject_CallMethod(obj, "__array__", NULL);
        if(ip && PyArray_Check(ip)) {
            dtype = PyArray_DESCR((PyArrayObject *)ip);
            Py_INCREF(dtype);
            Py_DECREF(ip);
            goto promote_types;
        }
        Py_XDECREF(ip);
        if (PyErr_Occurred()) {
            goto fail;
        }
    }

    /* Not exactly sure what this is about... */
#if !defined(NPY_PY3K)
    if (PyInstance_Check(obj)) {
        dtype = _use_default_type(obj);
        if (dtype == NULL) {
            goto fail;
        }
        else {
            goto promote_types;
        }
    }
#endif

    /*
     * If we reached the maximum recursion depth without hitting one
     * of the above cases, the output dtype should be OBJECT
     */
    if (maxdims == 0 || !PySequence_Check(obj)) {
        if (*out_dtype == NULL || (*out_dtype)->type_num != NPY_OBJECT) {
            Py_XDECREF(*out_dtype);
            *out_dtype = PyArray_DescrFromType(NPY_OBJECT);
            if (*out_dtype == NULL) {
                return -1;
            }
        }
        return 0;
    }

    /* Recursive case */
    size = PySequence_Size(obj);
    if (size < 0) {
        goto fail;
    }
    /* Recursive call for each sequence item */
    for (i = 0; i < size; ++i) {
        ip = PySequence_GetItem(obj, i);
        if (ip==NULL) {
            goto fail;
        }
        if (PyArray_DTypeFromObject(ip, maxdims - 1,
                            out_contains_na, out_dtype) < 0) {
            Py_DECREF(ip);
            goto fail;
        }
        Py_DECREF(ip);
    }

    return 0;


promote_types:
    /* Set 'out_dtype' if it's NULL */
    if (*out_dtype == NULL) {
        *out_dtype = dtype;
        return 0;
    }
    /* Do type promotion with 'out_dtype' */
    else {
        PyArray_Descr *res_dtype = PyArray_PromoteTypes(dtype, *out_dtype);
        Py_DECREF(dtype);
        if (res_dtype == NULL) {
            return -1;
        }
        Py_DECREF(*out_dtype);
        *out_dtype = res_dtype;
        return 0;
    }

fail:
    Py_XDECREF(*out_dtype);
    *out_dtype = NULL;
    return -1;
}