Esempio n. 1
0
static int emit_code_object(PyCodeObject *co)
{
    char buf[MAX_FUNC_NAME + 1];
    char *co_name, *co_filename;
    int co_firstlineno;
    int sz;
#if PY_MAJOR_VERSION >= 3
    co_name = PyUnicode_AsUTF8(co->co_name);
    if (co_name == NULL)
        return -1;
    co_filename = PyUnicode_AsUTF8(co->co_filename);
    if (co_filename == NULL)
        return -1;
#else
    co_name = PyString_AS_STRING(co->co_name);
    co_filename = PyString_AS_STRING(co->co_filename);
#endif
    co_firstlineno = co->co_firstlineno;

    sz = snprintf(buf, MAX_FUNC_NAME / 2, "py:%s", co_name);
    if (sz < 0) sz = 0;
    if (sz > MAX_FUNC_NAME / 2) sz = MAX_FUNC_NAME / 2;
    snprintf(buf + sz, MAX_FUNC_NAME / 2, ":%d:%s", co_firstlineno,
             co_filename);
    return vmprof_register_virtual_function(buf, CODE_ADDR_TO_UID(co), 500000);
}
Esempio n. 2
0
PyObject *_ped_Device_str(_ped_Device *self) {
    char *ret = NULL;
    char *hw_geom = NULL, *bios_geom = NULL;

    hw_geom = (char *) PyUnicode_AsUTF8(_ped_CHSGeometry_Type_obj.tp_repr(self->hw_geom));
    if (hw_geom == NULL) {
        return NULL;
    }

    bios_geom = (char *) PyUnicode_AsUTF8(_ped_CHSGeometry_Type_obj.tp_repr(self->bios_geom));
    if (bios_geom == NULL) {
        return NULL;
    }

    if (asprintf(&ret, "_ped.Device instance --\n"
                       "  model: %s  path: %s  type: %lld\n"
                       "  sector_size: %lld  phys_sector_size: %lld\n"
                       "  length: %lld  open_count: %d  read_only: %d\n"
                       "  external_mode: %d  dirty: %d  boot_dirty: %d\n"
                       "  host: %hd  did: %hd\n"
                       "  hw_geom: %s  bios_geom: %s",
                 self->model, self->path, self->type,
                 self->sector_size, self->phys_sector_size,
                 self->length, self->open_count, self->read_only,
                 self->external_mode, self->dirty, self->boot_dirty,
                 self->host, self->did,
                 hw_geom, bios_geom) == -1) {
        return PyErr_NoMemory();
    }

    return Py_BuildValue("s", ret);
}
Esempio n. 3
0
static PyObject* PyMinqlx_Kick(PyObject* self, PyObject* args) {
    int i;
    PyObject* reason;
    if (!PyArg_ParseTuple(args, "iO:kick", &i, &reason))
        return NULL;

	if (i >= 0 && i < sv_maxclients->integer) {
		if (svs->clients[i].state != CS_ACTIVE) {
			PyErr_Format(PyExc_ValueError,
					"client_id must be None or the ID of an active player.");
			return NULL;
		}
		else if (reason == Py_None || (PyUnicode_Check(reason) && PyUnicode_AsUTF8(reason)[0] == 0)) {
			// Default kick message for None or empty strings.
			SV_DropClient(&svs->clients[i], "was kicked.");
		}
		else if (PyUnicode_Check(reason)) {
			SV_DropClient(&svs->clients[i], PyUnicode_AsUTF8(reason));
		}
	}
	else {
		PyErr_Format(PyExc_ValueError,
				"client_id needs to be a number from 0 to %d, or None.",
				sv_maxclients->integer);
		return NULL;
	}

    Py_RETURN_NONE;
}
Esempio n. 4
0
void
_PyModule_ClearDict(PyObject *d)
{
    /* To make the execution order of destructors for global
       objects a bit more predictable, we first zap all objects
       whose name starts with a single underscore, before we clear
       the entire dictionary.  We zap them by replacing them with
       None, rather than deleting them from the dictionary, to
       avoid rehashing the dictionary (to some extent). */

    Py_ssize_t pos;
    PyObject *key, *value;

    /* First, clear only names starting with a single underscore */
    pos = 0;
    while (PyDict_Next(d, &pos, &key, &value)) {
        if (value != Py_None && PyUnicode_Check(key)) {
            if (PyUnicode_READ_CHAR(key, 0) == '_' &&
                PyUnicode_READ_CHAR(key, 1) != '_') {
                if (Py_VerboseFlag > 1) {
                    const char *s = PyUnicode_AsUTF8(key);
                    if (s != NULL)
                        PySys_WriteStderr("#   clear[1] %s\n", s);
                    else
                        PyErr_Clear();
                }
                if (PyDict_SetItem(d, key, Py_None) != 0)
                    PyErr_Clear();
            }
        }
    }

    /* Next, clear all names except for __builtins__ */
    pos = 0;
    while (PyDict_Next(d, &pos, &key, &value)) {
        if (value != Py_None && PyUnicode_Check(key)) {
            if (PyUnicode_READ_CHAR(key, 0) != '_' ||
                !_PyUnicode_EqualToASCIIString(key, "__builtins__"))
            {
                if (Py_VerboseFlag > 1) {
                    const char *s = PyUnicode_AsUTF8(key);
                    if (s != NULL)
                        PySys_WriteStderr("#   clear[2] %s\n", s);
                    else
                        PyErr_Clear();
                }
                if (PyDict_SetItem(d, key, Py_None) != 0)
                    PyErr_Clear();
            }
        }
    }

    /* Note: we leave __builtins__ in place, so that destructors
       of non-global objects defined in this module can still use
       builtins, in particularly 'None'. */

}
static PyObject *
XArgv(PyObject *dummy, PyObject *args) {
  int i;
  char **ptr;
  PyObject *list_object;
  int ifd;
  int len;
  int ret;
  char **argv;
  UNUSED(dummy);
  if (!PyArg_ParseTuple(args, "iO!", &ifd, &PyList_Type, &list_object))
    return NULL;
  len = PyList_Size(list_object);
  argv = ptr = (char **) calloc((size_t) len + 1, sizeof (char *));
  if (ptr == NULL) {
    return PyErr_NoMemory();
  }
  argv[len] = NULL;
  for (i = 0; i < len; i++) {
    PyObject *string_object;
    string_object = PyList_GetItem(list_object, i); /* borrowed ref */
/* TODO do it properly, catch exceptions for fancy Unicode symbols */
    argv[i] = PyUnicode_AsUTF8(string_object);    /* does not increase
                                                     ref count */
  }
  ret = dcc_x_argv(ifd, "ARGC", "ARGV", argv);
  free(argv);
  if (ret == 0)
    Py_RETURN_TRUE;
  else
    Py_RETURN_FALSE;
}
Esempio n. 6
0
/* Preferred access to parser is through AST. */
static mod_ty
string_object_to_c_ast(const char *s, PyObject *filename, int start,
                             PyCompilerFlags *flags, PyArena *arena)
{
    mod_ty mod;
    PyCompilerFlags localflags;
    perrdetail err;
    int iflags = PARSER_FLAGS(flags);

    node *n = Ta27Parser_ParseStringObject(s, filename,
                                         &_Ta27Parser_Grammar, start, &err,
                                         &iflags);
    if (flags == NULL) {
        localflags.cf_flags = 0;
        flags = &localflags;
    }
    if (n) {
        flags->cf_flags |= iflags & PyCF_MASK;
        mod = Ta27AST_FromNode(n, flags, PyUnicode_AsUTF8(filename), arena);
        Ta27Node_Free(n);
    }
    else {
        err_input(&err);
        mod = NULL;
    }
    err_free(&err);
    return mod;
}
Esempio n. 7
0
static PyObject *
py_set_metric(PyObject *Py_UNUSED(self), PyObject *args)
{
    PyObject *metric_object;

    if (!PyArg_ParseTuple(args, "O", &metric_object)) {
        return NULL;
    }

    if (PyUnicode_Check(metric_object)) {
        char *metric = PyUnicode_AsUTF8(metric_object);
        if (strcmp("euclidian", metric) == 0) {
            set_distance_metric(0);
        } else if (strcmp("cosine", metric) == 0) {
            set_distance_metric(1);
        } else {
            PyErr_SetString(PyExc_ValueError, "Invalid metric string value");
            return NULL;
        }
    } else if (PyCallable_Check(metric_object)) {
        Py_XDECREF(python_metric);
        Py_XINCREF(metric_object);
        python_metric = metric_object;
        distance_metric = python_distance;
    } else {
        PyErr_SetString(PyExc_TypeError, "Invalid metric type");
        return NULL;
    }

    Py_INCREF(Py_None);
    return Py_None;
}
Esempio n. 8
0
/* Convert a Python string (including Unicode in Py2 and Bytes in Py3) to a QString */
QString PyString_AsQString(PyObject *pystr)
{
    // Unicode
    if (PyUnicode_Check(pystr))
    {
#if PY_MAJOR_VERSION >= 3
        QString s = QString::fromUtf8(PyUnicode_AsUTF8(pystr));
#else
        PyObject *utf8str = PyUnicode_AsUTF8String(pystr);
        QString s = QString::fromUtf8(PyString_AsString(utf8str));
        Py_DecRef(utf8str);
#endif
        return s;
    }

    // Bytes
#if PY_MAJOR_VERSION >= 3
    else if (PyByteArray_Check(pystr))
        return QString::fromUtf8(PyByteArray_AsString(pystr));
#else
    else if (PyString_Check(pystr))
        return QString::fromUtf8(PyString_AsString(pystr));
#endif
    else
        return QString();
}
Esempio n. 9
0
/* Convert 9-item tuple to tm structure.  Return 1 on success, set
 * an exception and return 0 on error.
 */
static int
gettmarg(PyObject *args, struct tm *p)
{
    int y;

    memset((void *) p, '\0', sizeof(struct tm));

    if (!PyTuple_Check(args)) {
        PyErr_SetString(PyExc_TypeError,
                        "Tuple or struct_time argument required");
        return 0;
    }

    if (!PyArg_ParseTuple(args, "iiiiiiiii",
                          &y, &p->tm_mon, &p->tm_mday,
                          &p->tm_hour, &p->tm_min, &p->tm_sec,
                          &p->tm_wday, &p->tm_yday, &p->tm_isdst))
        return 0;
    p->tm_year = y - 1900;
    p->tm_mon--;
    p->tm_wday = (p->tm_wday + 1) % 7;
    p->tm_yday--;
#ifdef HAVE_STRUCT_TM_TM_ZONE
    if (Py_TYPE(args) == &StructTimeType) {
        PyObject *item;
        item = PyTuple_GET_ITEM(args, 9);
        p->tm_zone = item == Py_None ? NULL : PyUnicode_AsUTF8(item);
        item = PyTuple_GET_ITEM(args, 10);
        p->tm_gmtoff = item == Py_None ? 0 : PyLong_AsLong(item);
        if (PyErr_Occurred())
            return 0;
    }
#endif /* HAVE_STRUCT_TM_TM_ZONE */
    return 1;
}
Esempio n. 10
0
void OutputHook::call(std::string name, boost::python::object obj)
{
    Hooks::checkName(name);

    auto repr_ = PyObject_Repr(obj.ptr());
    if (PyErr_Occurred())
    {
        PyErr_Clear();
        throw Hooks::Exception("Failed to get __repr__ of argument");
    }
    auto repr = std::string(PyUnicode_AsUTF8(repr_));
    Py_DECREF(repr_);

    PyObject* g = Py_BuildValue(
            "{sO}", "__builtins__", PyEval_GetBuiltins());
    node->parent->loadDatumHooks(g);
    auto out = PyRun_String(repr.c_str(), Py_eval_input, g, g);
    Py_DECREF(g);
    Py_XDECREF(out);
    if (PyErr_Occurred())
    {
        PyErr_Clear();
        throw Hooks::Exception("Could not evaluate __repr__ of output");
    }

    const bool result = node->makeDatum(
            name, obj.ptr()->ob_type, Datum::SIGIL_OUTPUT + repr, true);

    if (!result)
        throw Hooks::Exception("Datum was already defined in this script.");
}
Esempio n. 11
0
static int
_posixshmem_shm_open_impl(PyObject *module, PyObject *path, int flags,
                          int mode)
/*[clinic end generated code: output=8d110171a4fa20df input=e83b58fa802fac25]*/
{
    int fd;
    int async_err = 0;
    const char *name = PyUnicode_AsUTF8(path);
    if (name == NULL) {
        return -1;
    }
    do {
        Py_BEGIN_ALLOW_THREADS
        fd = shm_open(name, flags, mode);
        Py_END_ALLOW_THREADS
    } while (fd < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));

    if (fd < 0) {
        if (!async_err)
            PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, path);
        return -1;
    }

    return fd;
}
static PyObject *py_ue_ihttp_request_set_content(ue_PyIHttpRequest *self, PyObject * args)
{

	PyObject *py_obj;
	if (!PyArg_ParseTuple(args, "O:set_content", &py_obj))
	{
		return NULL;
	}

	if (PyUnicode_Check(py_obj))
	{
		self->http_request->SetContentAsString(UTF8_TO_TCHAR(PyUnicode_AsUTF8(py_obj)));
	}
	else if (PyBytes_Check(py_obj))
	{
		char *buf = nullptr;
		Py_ssize_t len = 0;
		PyBytes_AsStringAndSize(py_obj, &buf, &len);
		TArray<uint8> data;
		data.Append((uint8 *)buf, len);
		self->http_request->SetContent(data);
	}

	Py_INCREF(Py_None);
	return Py_None;
}
Esempio n. 13
0
static int str2bank(PyObject *name)
{
    const char *text;

    if (PyBytes_Check(name))
        text = PyBytes_AsString(name);
#if PY_MAJOR_VERSION >= 3
    else if (PyUnicode_Check(name))
        text = PyUnicode_AsUTF8(name);
#endif
    else
    {
        PyErr_SetString(PyExc_TypeError, "expecting string");
        return 0;
    }

    if(strcmp(text, "reserved") == 0)
        return TMR_GEN2_BANK_RESERVED_ENABLED;
    else if(strcmp(text, "epc") == 0)
        return TMR_GEN2_BANK_EPC | TMR_GEN2_BANK_EPC_ENABLED;
    else if(strcmp(text, "tid") == 0)
        return TMR_GEN2_BANK_TID | TMR_GEN2_BANK_TID_ENABLED;
    else if(strcmp(text, "user") == 0)
        return TMR_GEN2_BANK_USER | TMR_GEN2_BANK_USER_ENABLED;
    else
    {
        PyErr_SetString(PyExc_TypeError, "invalid bank name");
        return 0;
    }
}
char* __PyString_AsString(PyObject *obj) {
#if PY_MAJOR_VERSION >= 3
    return PyUnicode_AsUTF8(obj);
#else
    return PyString_AsString(obj);
#endif
}
Esempio n. 15
0
node *
Ta27Parser_ParseStringObject(const char *s, PyObject *filename,
                           grammar *g, int start,
                           perrdetail *err_ret, int *flags)
{
    struct tok_state *tok;
    int exec_input = start == file_input;

    initerr_object(err_ret, filename);

    if (*flags & PyPARSE_IGNORE_COOKIE)
        tok = Ta27Tokenizer_FromUTF8(s, exec_input);
    else
        tok = Ta27Tokenizer_FromString(s, exec_input);

    if (tok == NULL) {
        err_ret->error = PyErr_Occurred() ? E_DECODE : E_NOMEM;
        return NULL;
    }

#ifndef PGEN
    Py_INCREF(err_ret->filename);
    tok->filename = PyUnicode_AsUTF8(err_ret->filename);
#endif
    return parsetok(tok, g, start, err_ret, flags);
}
Esempio n. 16
0
static char*
get_codec_name(const char *encoding)
{
    const char *name_utf8;
    char *name_str;
    PyObject *codec, *name = NULL;

    codec = _PyCodec_Lookup(encoding);
    if (!codec)
        goto error;

    name = _PyObject_GetAttrId(codec, &PyId_name);
    Py_CLEAR(codec);
    if (!name)
        goto error;

    name_utf8 = PyUnicode_AsUTF8(name);
    if (name_utf8 == NULL)
        goto error;
    name_str = _PyMem_RawStrdup(name_utf8);
    Py_DECREF(name);
    if (name_str == NULL) {
        PyErr_NoMemory();
        return NULL;
    }
    return name_str;

error:
    Py_XDECREF(codec);
    Py_XDECREF(name);
    return NULL;
}
Esempio n. 17
0
std::pair<std::string, int> getPyError()
{
    std::string error_traceback;
    int error_lineno = -1;

    PyObject *ptype, *pvalue, *ptraceback;
    PyErr_Fetch(&ptype, &pvalue, &ptraceback);

    // Extract the error's line number, with special case
    // for when we aren't given a traceback.
    if (ptraceback)
    {
        PyObject* lineno = PyObject_GetAttrString(ptraceback, "tb_lineno");
        error_lineno = PyLong_AsLong(lineno);
        Py_DECREF(lineno);
    } else {
        error_lineno = PyLong_AsLong(PyTuple_GetItem(
                                     PyTuple_GetItem(pvalue, 1), 1));
    }

    // Call traceback.format_exception on the traceback.
    PyErr_NormalizeException(&ptype, &pvalue, &ptraceback);

    PyObject* tbmod = PyImport_ImportModule("traceback");
    assert(tbmod);

    PyObject* format_func = PyObject_GetAttrString(tbmod, "format_exception");
    assert(format_func);

    if (!ptraceback)
    {
        ptraceback = Py_None;
        Py_INCREF(Py_None);
    }

    PyObject* args = Py_BuildValue("(OOO)", ptype, pvalue, ptraceback);
    PyObject* lst = PyObject_CallObject(format_func, args);

    // Concatenate the traceback list into a QString.
    error_traceback = "";
    for (int i=0; i < PyList_Size(lst); ++i)
    {
        char* c = PyUnicode_AsUTF8(PyList_GetItem(lst, i));
        assert(!PyErr_Occurred());
        error_traceback += std::string(c);
    }

    // Chop off the trailing "\n"
    error_traceback.pop_back();

    // ...and clean up all of the Python objects.
    for (auto a : {args, tbmod, lst, format_func})
        Py_DECREF(a);

    for (auto a : {ptype, pvalue, ptraceback})
        Py_XDECREF(a);

    return std::make_pair(error_traceback, error_lineno);
}
Esempio n. 18
0
static PyObject* Majka_find(Majka* self, PyObject* args, PyObject* kwds) {
  const char* word = NULL;
  char* results = new char[self->majka->max_results_size];
  const char* entry, * colon, * negative;
  char tmp_lemma[300];
  PyObject* ret = PyList_New(0);
  PyObject* lemma, * tags, * option;
  int rc, i;

  static char* kwlist[] = {const_cast<char*>("word"), NULL};

  if (!PyArg_ParseTupleAndKeywords(args, kwds, "|s", kwlist, &word)) {
    delete [] results;
    return NULL;
  }

  rc = self->majka->find(word, results, self->flags);

  if (rc == 0) {
    delete [] results;
    return ret;
  }

  if (self->first_only) rc = 1;

#ifdef PY3K
  negative = PyUnicode_AsUTF8(self->negative);
#else
  negative = PyString_AsString(self->negative);
#endif

  for (entry = results, i=0; i < rc; i++, entry += strlen(entry) + 1) {
    colon = strchr(entry, ':');
    memcpy(tmp_lemma, entry, colon-entry);
    tmp_lemma[colon-entry] = '\0';

    if (self->tags) {
      lemma = PyUnicode_FromString(tmp_lemma);
      tags = Majka_tags(colon+1);
      option = Py_BuildValue("{s:O,s:O}",
                             "lemma", lemma,
                             "tags", tags);
      Py_DECREF(lemma);
      Py_DECREF(tags);
    } else {
      if (is_negation(colon+1)){
        memmove(tmp_lemma+strlen(negative), tmp_lemma, strlen(tmp_lemma)+1);
        memcpy(tmp_lemma, negative, strlen(negative));
      }
      lemma = PyUnicode_FromString(tmp_lemma);
      option = Py_BuildValue("{s:O}",
                             "lemma", lemma);
      Py_DECREF(lemma);
    }
    list_append(ret, option);
  }
  delete [] results;
  return ret;
}
Esempio n. 19
0
const char *
PyModule_GetName(PyObject *m)
{
    PyObject *name = PyModule_GetNameObject(m);
    if (name == NULL)
        return NULL;
    Py_DECREF(name);   /* module dict has still a reference */
    return PyUnicode_AsUTF8(name);
}
Esempio n. 20
0
static void print_dict(PyObject *dict) {
	PyObject *keys = PyDict_Keys(dict);
	for (Py_ssize_t i = 0; i < PyList_Size(keys); ++i) {
		PyObject *key = PyList_GetItem(keys, i);
		debug("\t%s", PyUnicode_AsUTF8(key));
		Py_DECREF(key);
	}
	Py_DECREF(keys);
}
Esempio n. 21
0
std::string PyInterpreter::ToString(PyObject* py)
{
    PyUniqueObj pystr = PyObject_Repr(py);
#if PY_MAJOR_VERSION >= 3
    return std::string(PyUnicode_AsUTF8(pystr));
#else
    return std::string(PyString_AsString(pystr));
#endif
}
Esempio n. 22
0
PRBool PyXPCOM_FormatGivenException(nsCString &streamout,
				    PyObject *exc_typ, PyObject *exc_val,
				    PyObject *exc_tb)
{
	if (!exc_typ)
		return PR_FALSE;
	streamout += "\n";

	if (exc_tb) {
		const char *szTraceback = PyTraceback_AsString(exc_tb);
		if (szTraceback == NULL)
			streamout += "Can't get the traceback info!";
		else {
			streamout += "Traceback (most recent call last):\n";
			streamout += szTraceback;
			PyMem_Free((void *)szTraceback);
		}
	}
	PyObject *temp = PyObject_Str(exc_typ);
	if (temp) {
#if PY_MAJOR_VERSION <= 2
		streamout += PyString_AsString(temp);
#else
		streamout += PyUnicode_AsUTF8(temp);
#endif
		Py_DECREF(temp);
	} else
		streamout += "Can't convert exception to a string!";
	streamout += ": ";
	if (exc_val != NULL) {
		temp = PyObject_Str(exc_val);
		if (temp) {
#if PY_MAJOR_VERSION <= 2
			streamout += PyString_AsString(temp);
#else
			streamout += PyUnicode_AsUTF8(temp);
#endif
			Py_DECREF(temp);
		} else
			streamout += "Can't convert exception value to a string!";
	}
	return PR_TRUE;
}
Esempio n. 23
0
static PyObject *PythonQtClassWrapper_getattro(PyObject *obj, PyObject *name)
{
  const char *attributeName;
  PythonQtClassWrapper *wrapper = (PythonQtClassWrapper *)obj;

#ifdef PY3K
  if ((attributeName = PyUnicode_AsUTF8(name)) == NULL) {
#else
  if ((attributeName = PyString_AsString(name)) == NULL) {
#endif
    return NULL;
  }
  if (obj == (PyObject*)&PythonQtInstanceWrapper_Type) {
    return NULL;
  }

  if (qstrcmp(attributeName, "__dict__")==0) {
    PyObject* objectDict  = ((PyTypeObject *)wrapper)->tp_dict;
    if (!wrapper->classInfo()) {
      Py_INCREF(objectDict);
      return objectDict;
    }
    PyObject* dict = PyDict_New();
      
    QStringList l = wrapper->classInfo()->memberList();
    Q_FOREACH (QString name, l) {
      PyObject* o = PyObject_GetAttrString(obj, name.toLatin1().data());
      if (o) {
        PyDict_SetItemString(dict, name.toLatin1().data(), o);
        Py_DECREF(o);
      } else {
        // it must have been a property or child, which we do not know as a class object...
        PyErr_Clear();
      }
    }
    if (wrapper->classInfo()->constructors()) {
#ifdef PY3K
      PyObject* initName = PyUnicode_FromString("__init__");
#else
      PyObject* initName = PyString_FromString("__init__");
#endif
      PyObject* func = PyType_Type.tp_getattro(obj, initName);
      Py_DECREF(initName);
      PyDict_SetItemString(dict, "__init__", func);
      Py_DECREF(func);
    }
    for (int i = 0; PythonQtClassWrapper_methods[i].ml_name != NULL; i++) {
      PyObject* func = PyCFunction_New(&PythonQtClassWrapper_methods[i], obj);
      PyDict_SetItemString(dict, PythonQtClassWrapper_methods[i].ml_name, func);
      Py_DECREF(func);
    }

    PyDict_Update(dict, objectDict);
    return dict;
  }
static int py_ue_edgraphpin_set_default_text_value(ue_PyEdGraphPin *self, PyObject *value, void *closure)
{
	if (value && PyUnicode_Check(value))
	{
		char *str = PyUnicode_AsUTF8(value);
		self->pin->DefaultTextValue = FText::FromString(UTF8_TO_TCHAR(str));
		return 0;
	}
	PyErr_SetString(PyExc_TypeError, "value is not a string");
	return -1;
}
Esempio n. 25
0
PyObject *_ped_Constraint_str(_ped_Constraint *self) {
    char *ret = NULL;
    char *start_align = NULL, *end_align = NULL;
    char *start_range = NULL, *end_range = NULL;

    start_align =
PyUnicode_AsUTF8(_ped_Alignment_Type_obj.tp_repr(self->start_align));
    if (start_align == NULL) {
        return NULL;
    }

    end_align =
PyUnicode_AsUTF8(_ped_Alignment_Type_obj.tp_repr(self->end_align));
    if (end_align == NULL) {
        return NULL;
    }

    start_range =
PyUnicode_AsUTF8(_ped_Geometry_Type_obj.tp_repr(self->start_range));
    if (start_range == NULL) {
        return NULL;
    }

    end_range =
PyUnicode_AsUTF8(_ped_Geometry_Type_obj.tp_repr(self->end_range));
    if (end_range == NULL) {
        return NULL;
    }

    if (asprintf(&ret, "_ped.Constraint instance --\n"
                       "  start_align: %s  end_align: %s\n"
                       "  start_range: %s  end_range: %s\n"
                       "  min_size: %lld  max_size: %lld",
                 start_align, end_align,
                 start_range, end_range,
                 self->min_size, self->max_size) == -1) {
        return PyErr_NoMemory();
    }

    return Py_BuildValue("s", ret);
}
Esempio n. 26
0
const char *
PyModule_GetFilename(PyObject *m)
{
    PyObject *fileobj;
    const char *utf8;
    fileobj = PyModule_GetFilenameObject(m);
    if (fileobj == NULL)
        return NULL;
    utf8 = PyUnicode_AsUTF8(fileobj);
    Py_DECREF(fileobj);   /* module dict has still a reference */
    return utf8;
}
Esempio n. 27
0
CString CGenethonDoc::handlePyError() {
    CString retVal = CString();

    PyObject* excType, *excValue, *excTraceback;
    PyErr_Fetch(&excType, &excValue, &excTraceback);
    PyErr_NormalizeException(&excType, &excValue, &excTraceback);

    CString callBacks = CString();
    CString work = CString();
    PyTracebackObject* ptraceback = (PyTracebackObject*)excTraceback;
    if (ptraceback != NULL) {
        work.Format("File: %s\nLine no: %d\n", PyUnicode_AsUTF8(PyObject_Str(((PyTracebackObject*)ptraceback)->tb_frame->f_code->co_filename)), ((PyTracebackObject*)ptraceback)->tb_lineno);
        callBacks.Append(work.GetString());
        // Advance to the last frame (python puts the most-recent call at the end)
        while (ptraceback->tb_next != NULL) {
            ptraceback = ptraceback->tb_next;
            work.Format("File: %s\nLine no: %d\n", PyUnicode_AsUTF8(PyObject_Str(((PyTracebackObject*)ptraceback)->tb_frame->f_code->co_filename)), ((PyTracebackObject*)ptraceback)->tb_lineno);
            callBacks.Append(work.GetString());
        }
        // At this point I have access to the line number via traceback->tb_lineno,
        // but where do I get the file name from?
        int line = ptraceback->tb_lineno;
    }
    retVal.Format("Error type: %s\n%s\nError: %s",
                  PyUnicode_AsUTF8(PyObject_Str(excType)),
                  callBacks.GetString(),
                  PyUnicode_AsUTF8(PyObject_Str(excValue))
                 );
    // Now you have two options, restoring the exception or disposing it.
    PyErr_Restore(excType, excValue, excTraceback);

    //---->

    Py_XDECREF(excType);
    Py_XDECREF(excValue);
    Py_XDECREF(excTraceback);

    return retVal;

}
Esempio n. 28
0
void foreach_tok(void *gen_toks, jieba_token_callbk callfun)
{
	PyObject *it = PyObject_GetIter(gen_toks); /* new ref */
	PyObject *tok = NULL;
	PyObject *py_term, *py_begin, *py_end, *py_tag;
	long int begin, end;
	char *term, *tag;

	if (it == NULL) {
		printf("PyObject_GetIter() fails.\n");
		return;
	}

	while (NULL != (tok /* new ref */ = PyIter_Next(it))) {
		assert(PyTuple_Check(tok) == 1);

		/* PyTuple_GetItem() returns borrowed
		 * reference, no need to call Py_DECREF() */
		py_term  = PyTuple_GetItem(tok, 0);
		py_begin = PyTuple_GetItem(tok, 1);
		py_end   = PyTuple_GetItem(tok, 2);
		py_tag   = PyTuple_GetItem(tok, 3);

		/* for PyUnicode_AsUTF8() the caller is not
		 * responsible for deallocating the buffer. */
		term  = PyUnicode_AsUTF8(py_term);
		begin = PyLong_AsLong(py_begin);
		end   = PyLong_AsLong(py_end);
		tag   = PyUnicode_AsUTF8(py_tag);

		callfun(term, begin, end, tag);
		// PRINT_REF_CNT(tok);
		Py_DECREF(tok);
	}

	printf("\n");
	//PRINT_REF_CNT(it);
	Py_DECREF(it);
}
Esempio n. 29
0
		PyEvent * PyManager::createEvent(PyHandle pyName)
		{
			auto pEvent = new PyEvent;
			pEvent->szName = PyUnicode_AsUTF8(pyName);
			pEvent->PyStrName.save(pyName);

			// Call default event
			if (auto pEvent = PyManager::getEvent("create_event"))
				pEvent->call("s", { const_cast<char*>(pEvent->szName) });

			g_events.push_back(pEvent);
			return pEvent;
		}
Esempio n. 30
0
PyObject *term_to_nametuple(const char *s, int arity, term_t t) {
  PyObject *o;
#if PY_MAJOR_VERSION >= 3
  PyTypeObject *typp;
  PyObject *key = PyUnicode_FromString(s);
  if (py_F2P && PyDict_Contains(py_F2P, key)) {
    typp = (PyTypeObject *)PyDict_GetItem(py_F2P, key);
  } else {

    typp = PyMem_Malloc(sizeof(PyTypeObject));
    PyStructSequence_Desc *desc = PyMem_Malloc(sizeof(PyStructSequence_Desc));

    desc->name = PyUnicode_AsUTF8(key);
    desc->doc = "YAPTerm";
    desc->fields = pnull;
    desc->n_in_sequence = 32;
    if (PyStructSequence_InitType2(typp, desc) < 0)
      return NULL;
    typp->tp_str = structseq_str;
    typp->tp_repr = structseq_repr;
    //     typp = PyStructSequence_NewType(desc);
    Py_INCREF(typp);
    //	typp->tp_flags |= Py_TPFLAGS_HEAPTYPE;
    PyModule_AddObject(py_Yapex, s, (PyObject *)typp);
    if (py_F2P)
      PyDict_SetItem(py_F2P, key, (PyObject *)typp);
  }
  o = PyTuple_New(typp);
#else
  o = PyTuple_New(arity);
#endif
  term_t tleft = PL_new_term_ref();
  int i;

  for (i = 0; i < arity; i++) {
    PyObject *pArg;
    if (!PL_get_arg(i + 1, t, tleft))
      return NULL;
    pArg = term_to_python(tleft, false);
    if (pArg == NULL)
      return NULL;
#if PY_MAJOR_VERSION >= 3
    /* pArg reference stolen here: */
    PyStructSequence_SET_ITEM(o, i, pArg);
  }
  ((PyStructSequence *)o)->ob_base.ob_size = arity;
  return o;
#else
    /* pArg reference stolen here: */
    PyTuple_SET_ITEM(o, i, pArg);
  }