Esempio n. 1
0
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;
    }
}
Esempio n. 2
0
static inline const char*pystring_asstring(PyObject*s)
{
#ifdef PYTHON3
    return PyUnicode_AS_DATA(s);
#else
    return PyString_AsString(s);
#endif
}
Esempio n. 3
0
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;
}
Esempio n. 4
0
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;
}
Esempio n. 5
0
/* 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;
}
Esempio n. 6
0
NPY_NO_EXPORT void *
scalar_value(PyObject *scalar, PyArray_Descr *descr)
{
    int type_num;
    int align;
    intp memloc;
    if (descr == NULL) {
        descr = PyArray_DescrFromScalar(scalar);
        type_num = descr->type_num;
        Py_DECREF(descr);
    }
    else {
        type_num = descr->type_num;
    }
    switch (type_num) {
#define CASE(ut,lt) case NPY_##ut: return &(((Py##lt##ScalarObject *)scalar)->obval)
        CASE(BOOL, Bool);
        CASE(BYTE, Byte);
        CASE(UBYTE, UByte);
        CASE(SHORT, Short);
        CASE(USHORT, UShort);
        CASE(INT, Int);
        CASE(UINT, UInt);
        CASE(LONG, Long);
        CASE(ULONG, ULong);
        CASE(LONGLONG, LongLong);
        CASE(ULONGLONG, ULongLong);
        CASE(FLOAT, Float);
        CASE(DOUBLE, Double);
        CASE(LONGDOUBLE, LongDouble);
        CASE(CFLOAT, CFloat);
        CASE(CDOUBLE, CDouble);
        CASE(CLONGDOUBLE, CLongDouble);
        CASE(OBJECT, Object);
        CASE(DATETIME, Datetime);
        CASE(TIMEDELTA, Timedelta);
#undef CASE
        case NPY_STRING:
            return (void *)PyString_AS_STRING(scalar);
        case NPY_UNICODE:
            return (void *)PyUnicode_AS_DATA(scalar);
        case NPY_VOID:
            return ((PyVoidScalarObject *)scalar)->obval;
    }

    /*
     * Must be a user-defined type --- check to see which
     * scalar it inherits from.
     */

#define _CHK(cls) (PyObject_IsInstance(scalar, \
            (PyObject *)&Py##cls##ArrType_Type))
#define _OBJ(lt) &(((Py##lt##ScalarObject *)scalar)->obval)
#define _IFCASE(cls) if _CHK(cls) return _OBJ(cls)

    if _CHK(Number) {
        if _CHK(Integer) {
            if _CHK(SignedInteger) {
                _IFCASE(Byte);
                _IFCASE(Short);
                _IFCASE(Int);
                _IFCASE(Long);
                _IFCASE(LongLong);
		if _CHK(TimeInteger) {
		    _IFCASE(Datetime);
		    _IFCASE(Timedelta);
		}
            }
            else {
                /* Unsigned Integer */
                _IFCASE(UByte);
                _IFCASE(UShort);
                _IFCASE(UInt);
                _IFCASE(ULong);
                _IFCASE(ULongLong);
            }
        }
        else {
            /* Inexact */
            if _CHK(Floating) {
Esempio n. 7
0
    Model buildModel(const std::string & filename, const std::string & model_name, bool verbose) throw (bp::error_already_set)
    {
      Py_Initialize();

      bp::object main_module = bp::import("__main__");
      // Get a dict for the global namespace to exec further python code with
      bp::dict globals = bp::extract<bp::dict>(main_module.attr("__dict__"));

      // We need to link to the pinocchio PyWrap. We delegate the dynamic loading to the python interpreter.
      bp::object cpp_module( (bp::handle<>(bp::borrowed(PyImport_AddModule("libpinocchio_pywrap")))) );

      // That's it, you can exec your python script, starting with a model you
      // can update as you want.
      try
      {
// Boost 1.58
#if BOOST_VERSION / 100 % 1000 == 58
        // Avoid a segv with exec_file
        // See: https://github.com/boostorg/python/pull/15
        std::ifstream t(filename.c_str());
        std::stringstream buffer;
        buffer << t.rdbuf();
        bp::exec(buffer.str().c_str(), globals);
#else // default implementation
        bp::exec_file((bp::str)filename, globals);
#endif
      }
      catch (bp::error_already_set & e)
      {
        PyErr_PrintEx(0);
      }

      Model model;
      try
      {
        bp::object obj_model = globals[model_name];
        model = bp::extract<Model>(obj_model);
      }
      catch (bp::error_already_set & e)
      {
        PyErr_PrintEx(0);
      }
      if (verbose)
      {
        std::cout << "Your model has been built. It has " << model.nv;
        std::cout << " degrees of freedom." << std::endl;
      }

      // close the interpreter
      // cf. https://github.com/numpy/numpy/issues/8097
#if PY_MAJOR_VERSION < 3
      Py_Finalize();
#else

      PyObject * poMainModule = PyImport_AddModule("__main__");
      PyObject * poAttrList = PyObject_Dir(poMainModule);
      PyObject * poAttrIter = PyObject_GetIter(poAttrList);
      PyObject * poAttrName;

      while ((poAttrName = PyIter_Next(poAttrIter)) != NULL)
      {
        std::string oAttrName = PyUnicode_AS_DATA(poAttrName);

        // Make sure we don't delete any private objects.
        if (!boost::starts_with(oAttrName, "__") || !boost::ends_with(oAttrName, "__"))
        {
          PyObject * poAttr = PyObject_GetAttr(poMainModule, poAttrName);

          // Make sure we don't delete any module objects.
          if (poAttr && poAttr->ob_type != poMainModule->ob_type)
            PyObject_SetAttr(poMainModule, poAttrName, NULL);
          Py_DecRef(poAttr);
        }
        Py_DecRef(poAttrName);
      }
      Py_DecRef(poAttrIter);
      Py_DecRef(poAttrList);
#endif

      return model;
    }
Esempio n. 8
0
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;
}