コード例 #1
0
static PyObject *
Spec_providedBy(PyObject *self, PyObject *ob)
{
    PyObject *decl, *item;

    decl = providedBy(NULL, ob);
    if (decl == NULL)
        return NULL;

    if (PyObject_TypeCheck(decl, &SpecType))
        item = Spec_extends(decl, self);
    else
        /* decl is probably a security proxy.  We have to go the long way
           around.
        */
        item = PyObject_CallFunctionObjArgs(decl, self, NULL);

    Py_DECREF(decl);
    return item;
}
コード例 #2
0
ファイル: bpy_internal_import.c プロジェクト: 244xiao/blender
static PyObject *blender_reload(PyObject *UNUSED(self), PyObject *module)
{
	PyObject *exception, *err, *tb;
	PyObject *newmodule = NULL;
	int found = 0;

	/* try reimporting from file */

	/* in Py3.3 this just calls imp.reload() which we overwrite, causing recursive calls */
	//newmodule = PyImport_ReloadModule(module);

	newmodule = PyObject_CallFunctionObjArgs(imp_reload_orig, module, NULL);

	if (newmodule)
		return newmodule;

	/* no file, try importing from memory */
	PyErr_Fetch(&exception, &err, &tb); /*restore for probable later use */

	newmodule = bpy_text_reimport(module, &found);
	if (newmodule) { /* found module as blender text, ignore above exception */
		PyErr_Clear();
		Py_XDECREF(exception);
		Py_XDECREF(err);
		Py_XDECREF(tb);
		/* printf("imported from text buffer...\n"); */
	}
	else if (found == 1) { /* blender text module failed to execute but was found, use its error message */
		Py_XDECREF(exception);
		Py_XDECREF(err);
		Py_XDECREF(tb);
		return NULL;
	}
	else {
		/* no blender text was found that could import the module
		 * reuse the original error from PyImport_ImportModuleEx */
		PyErr_Restore(exception, err, tb);
	}

	return newmodule;
}
コード例 #3
0
ファイル: modpython.cpp プロジェクト: ZachBeta/znc
	CString GetPyExceptionStr() {
			PyObject* ptype;
			PyObject* pvalue;
			PyObject* ptraceback;
			PyErr_Fetch(&ptype, &pvalue, &ptraceback);
			CString result;
			if (!pvalue) {
				Py_INCREF(Py_None);
				pvalue = Py_None;
			}
			if (!ptraceback) {
				Py_INCREF(Py_None);
				ptraceback = Py_None;
			}
			PyErr_NormalizeException(&ptype, &pvalue, &ptraceback);
			PyObject* strlist = PyObject_CallFunctionObjArgs(m_PyFormatException, ptype, pvalue, ptraceback, NULL);
			Py_CLEAR(ptype);
			Py_CLEAR(pvalue);
			Py_CLEAR(ptraceback);
			if (!strlist) {
				return "Couldn't get exact error message";
			}

			if (PySequence_Check(strlist)) {
				PyObject* strlist_fast = PySequence_Fast(strlist, "Shouldn't happen (1)");
				PyObject** items = PySequence_Fast_ITEMS(strlist_fast);
				Py_ssize_t L = PySequence_Fast_GET_SIZE(strlist_fast);
				for (Py_ssize_t i = 0; i < L; ++i) {
					PyObject* utf8 = PyUnicode_AsUTF8String(items[i]);
					result += PyBytes_AsString(utf8);
					Py_CLEAR(utf8);
				}
				Py_CLEAR(strlist_fast);
			} else {
				result = "Can't get exact error message";
			}

			Py_CLEAR(strlist);

			return result;
	}
コード例 #4
0
ファイル: capsule.cpp プロジェクト: KennethNielsen/llvmpy
static
PyObject* WrapCore(PyObject *oldCap, bool owned) {
    auto_pyobject cap = PyObject_CallFunctionObjArgs(GetCapsuleClass(), oldCap,
                                                     NULL);
    auto_pyobject cls = PyObject_CallMethod(*cap, "get_class", "");
    auto_pyobject addr = GetPointer(oldCap);

    // look up cached object
    auto_pyobject cache_cls = PyObject_GetItem(GetCache(), *cls);
    Assert(*cache_cls);
    PyObject* obj = NULL;

    obj = PyObject_GetItem(*cache_cls, *addr);

    if (obj) {
        /* cache hit */
    }
    else {
        if (!PyErr_ExceptionMatches(PyExc_KeyError))
            return NULL;
        /* cache miss */
        PyErr_Clear();
        if (!owned) {
            auto_pyobject hasDtor = PyObject_CallMethod(*cls, "_has_dtor", "");
            if (PyObject_IsTrue(*hasDtor)) {
                auto_pyobject name = GetName(oldCap);
                auto_pyobject key = PyTuple_Pack(2, *name, *addr);
                auto_pyobject val = PyObject_GetAttrString(*cls, "_delete_");

                int ok = PyDict_SetItem(GetAddrDtorDict(), *key, *val);
                Assert(ok != -1);
            }
        }
        obj = PyObject_CallMethod(*cap, "instantiate", "");
        int ok = PyObject_SetItem(*cache_cls, *addr, obj);
        Assert(ok != -1);
    }

    Assert(obj);
    return obj;
}
コード例 #5
0
static PyObject *
search_pp_list (PyObject *list, PyObject *value)
{
    Py_ssize_t pp_list_size, list_index;
    PyObject *function, *printer = NULL;

    pp_list_size = PyList_Size (list);
    for (list_index = 0; list_index < pp_list_size; list_index++)
    {
        function = PyList_GetItem (list, list_index);
        if (! function)
            return NULL;

        /* Skip if disabled.  */
        if (PyObject_HasAttr (function, gdbpy_enabled_cst))
        {
            PyObject *attr = PyObject_GetAttr (function, gdbpy_enabled_cst);
            int cmp;

            if (!attr)
                return NULL;
            cmp = PyObject_IsTrue (attr);
            Py_DECREF (attr);
            if (cmp == -1)
                return NULL;

            if (!cmp)
                continue;
        }

        printer = PyObject_CallFunctionObjArgs (function, value, NULL);
        if (! printer)
            return NULL;
        else if (printer != Py_None)
            return printer;

        Py_DECREF (printer);
    }

    Py_RETURN_NONE;
}
コード例 #6
0
ファイル: cext.c プロジェクト: aRkadeFR/dotVim
static PyObject *Proxy__ensure_wrapped(ProxyObject *self)
{
    PyObject *wrapped;

    if (self->wrapped) {
        return self->wrapped;
    } else {
        if (self->factory) {
            wrapped = PyObject_CallFunctionObjArgs(self->factory, NULL);
            if (wrapped) {
                self->wrapped = wrapped;
                return wrapped;
            } else {
                return NULL;
            }
        } else {
            PyErr_SetString(PyExc_ValueError, "Proxy hasn't been initiated: __factory__ is missing.");
            return NULL;
        }
    }
}
コード例 #7
0
ファイル: rpmfd-py.c プロジェクト: Distrotech/rpm
int rpmfdFromPyObject(PyObject *obj, rpmfdObject **fdop)
{
    rpmfdObject *fdo = NULL;

    if (rpmfdObject_Check(obj)) {
	Py_INCREF(obj);
	fdo = (rpmfdObject *) obj;
    } else {
	fdo = (rpmfdObject *) PyObject_CallFunctionObjArgs((PyObject *)&rpmfd_Type,
                                                           obj, NULL);
    }
    if (fdo == NULL) return 0;

    if (Ferror(fdo->fd)) {
	PyErr_SetString(PyExc_IOError, Fstrerror(fdo->fd));
	Py_DECREF(fdo);
	return 0;
    }
    *fdop = fdo;
    return 1;
}
コード例 #8
0
ファイル: xid_type.c プロジェクト: psycopg/psycopg2
static PyObject *
_xid_base64_enc_dec(const char *funcname, PyObject *s)
{
    PyObject *base64 = NULL;
    PyObject *func = NULL;
    PyObject *rv = NULL;

    if (!(base64 = PyImport_ImportModule("base64"))) { goto exit; }
    if (!(func = PyObject_GetAttrString(base64, funcname))) { goto exit; }

    Py_INCREF(s);
    if (!(s = psyco_ensure_bytes(s))) { goto exit; }
    rv = psyco_ensure_text(PyObject_CallFunctionObjArgs(func, s, NULL));
    Py_DECREF(s);

exit:
    Py_XDECREF(func);
    Py_XDECREF(base64);

    return rv;
}
コード例 #9
0
ファイル: locks.c プロジェクト: chenbk85/jega
static int
RLockObject_init(RLockObject *self, PyObject *args, PyObject *kwargs)
{
    
    PyObject *s;
    DEBUG("self:%p", self);

    s = PyObject_CallFunctionObjArgs((PyObject*)&SemaphoreObjectType, NULL);
    if (s == NULL) {
        return -1;
    }
    Py_CLEAR(self->block);
    Py_CLEAR(self->owner);

    self->block = s;
    self->count = 0;
    self->owner = Py_None;
    Py_INCREF(self->owner);

    return 1;
}
コード例 #10
0
ファイル: py-event.c プロジェクト: Claruarius/stblinux-2.6.37
int
evpy_emit_event (PyObject *event,
                 eventregistry_object *registry)
{
  PyObject *callback_list_copy = NULL;
  Py_ssize_t i;

  /* Create a copy of call back list and use that for
     notifying listeners to avoid skipping callbacks
     in the case of a callback being disconnected during
     a notification.  */
  callback_list_copy = PySequence_List (registry->callbacks);
  if (!callback_list_copy)
    goto fail;

  for (i = 0; i < PyList_Size (callback_list_copy); i++)
    {
      PyObject *func = PyList_GetItem (callback_list_copy, i);

      if (func == NULL)
	goto fail;

      if (!PyObject_CallFunctionObjArgs (func, event, NULL))
	{
	  /* Print the trace here, but keep going -- we want to try to
	     call all of the callbacks even if one is broken.  */
	  gdbpy_print_stack ();
	}
    }

  Py_XDECREF (callback_list_copy);
  Py_XDECREF (event);
  return 0;

 fail:
  gdbpy_print_stack ();
  Py_XDECREF (callback_list_copy);
  Py_XDECREF (event);
  return -1;
}
コード例 #11
0
ファイル: _thunk.c プロジェクト: pombredanne/lazy_python
/* Strictly evaluate a thunk.
   return: A new reference. */
static PyObject *
strict_eval(PyObject *th)
{
    static PyObject *strict_name;
    PyObject *normal;
    PyObject *strict_method = NULL;

    if (PyObject_IsInstance(th, (PyObject*)  &thunk_type)) {
        if (!(th = _strict_eval_borrowed(th))) {
            return NULL;
        }
    }

    if (!(strict_name ||
          (strict_name = PyUnicode_FromString("__strict__")))) {
        return NULL;
    }
    if (!(strict_method = PyObject_GetAttr((PyObject*) Py_TYPE(th),
                                           strict_name))) {
        if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
            PyErr_Clear();
            normal = th;
        }
        else {
            return NULL;
        }
    }
    else if (!(normal = PyObject_CallFunctionObjArgs(strict_method,
                                                     th,
                                                     NULL))) {
        Py_DECREF(strict_method);
        return NULL;
    }
    else {
        Py_XDECREF(strict_method);
    }

    Py_INCREF(normal);
    return normal;
}
コード例 #12
0
ファイル: green.c プロジェクト: kikin/watchlrsite
/* Block waiting for data available in an async connection.
 *
 * This function assumes `wait_callback` to be available:
 * raise `InterfaceError` if it is not. Use `psyco_green()` to check if
 * the function is to be called.
 *
 * Return 0 on success, else nonzero and set a Python exception.
 */
int
psyco_wait(connectionObject *conn)
{
    PyObject *rv;
    PyObject *cb;

    Dprintf("psyco_wait");
    if (!(cb = have_wait_callback())) {
        return -1;
    }

    rv = PyObject_CallFunctionObjArgs(cb, conn, NULL);
    Py_DECREF(cb);

    if (NULL != rv) {
        Py_DECREF(rv);
        return 0;
    } else {
        Dprintf("psyco_wait: error in wait callback");
        return -1;
    }
}
コード例 #13
0
ファイル: _cthreading.c プロジェクト: mureinik/cthreading
static acquire_result
Condition_wait_released(Condition *self, struct waiter *waiter, double timeout)
{
    PyObject *saved_state = NULL;
    PyObject *r = NULL;
    acquire_result res;

    saved_state = PyObject_CallObject(self->release_save, NULL);
    if (saved_state == NULL)
        return ACQUIRE_ERROR;

    res = acquire_lock(&waiter->sem, timeout);

    r = PyObject_CallFunctionObjArgs(self->acquire_restore, saved_state, NULL);
    if (r == NULL)
        res = ACQUIRE_ERROR;

    Py_CLEAR(saved_state);
    Py_CLEAR(r);

    return res;
}
コード例 #14
0
ファイル: control.cpp プロジェクト: Highstaker/antimony
void Control::drag(QVector3D center, QVector3D diff)
{
    auto p = node->mutableProxy();
    auto x = PyFloat_FromDouble(relative ? diff.x() : center.x());
    auto y = PyFloat_FromDouble(relative ? diff.y() : center.y());
    auto z = PyFloat_FromDouble(relative ? diff.z() : center.z());

    if (drag_func)
    {
        PyObject_CallFunctionObjArgs(drag_func, p, x, y, z, NULL);
        if (PyErr_Occurred())
        {
            PyErr_Print();
            PyErr_Clear();
        }
    }

    Py_DECREF(p);
    Py_DECREF(x);
    Py_DECREF(y);
    Py_DECREF(z);
}
コード例 #15
0
ファイル: pipe.c プロジェクト: ayanamist/pyuv
static void
on_pipe_read2(uv_pipe_t* handle, int nread, uv_buf_t buf, uv_handle_type pending)
{
    PyGILState_STATE gstate = PyGILState_Ensure();
    uv_err_t err;
    Stream *self;
    PyObject *result, *data, *py_errorno, *py_pending;
    ASSERT(handle);

    self = (Stream *)handle->data;
    ASSERT(self);
    /* Object could go out of scope in the callback, increase refcount to avoid it */
    Py_INCREF(self);

    py_pending = PyInt_FromLong((long)pending);

    if (nread >= 0) {
        data = PyBytes_FromStringAndSize(buf.base, nread);
        py_errorno = Py_None;
        Py_INCREF(Py_None);
    } else {
        data = Py_None;
        Py_INCREF(Py_None);
        err = uv_last_error(UV_HANDLE_LOOP(self));
        py_errorno = PyInt_FromLong((long)err.code);
    }

    result = PyObject_CallFunctionObjArgs(self->on_read_cb, self, data, py_pending, py_errorno, NULL);
    if (result == NULL) {
        handle_uncaught_exception(HANDLE(self)->loop);
    }
    Py_XDECREF(result);
    Py_DECREF(data);
    Py_DECREF(py_pending);
    Py_DECREF(py_errorno);

    Py_DECREF(self);
    PyGILState_Release(gstate);
}
コード例 #16
0
static int on_body(http_parser* parser, const char *at, size_t length)
{
    int fail = 0;
    PyObject* self = (PyObject*)parser->data;
    if (PyObject_HasAttrString(self, "_on_body")) {
        PyObject* callable = PyObject_GetAttrString(self, "_on_body");
        PyObject* bytearray = PyByteArray_FromStringAndSize(at, length);
        PyObject* result = PyObject_CallFunctionObjArgs(
            callable, bytearray, NULL);
        PyObject* exception = PyErr_Occurred();
        if (exception != NULL) {
            fail = 1;
        } else {
            if (PyObject_IsTrue(result))
                fail = 1;
        }
        Py_XDECREF(result);
        Py_DECREF(callable);
        Py_DECREF(bytearray);
    }
    return fail;
}
コード例 #17
0
ファイル: timer.c プロジェクト: iyedb/pyuv
static void
on_timer_callback(uv_timer_t *handle)
{
    PyGILState_STATE gstate = PyGILState_Ensure();
    Timer *self;
    PyObject *result;

    ASSERT(handle);
    self = PYUV_CONTAINER_OF(handle, Timer, timer_h);

    /* Object could go out of scope in the callback, increase refcount to avoid it */
    Py_INCREF(self);

    result = PyObject_CallFunctionObjArgs(self->callback, self, NULL);
    if (result == NULL) {
        handle_uncaught_exception(HANDLE(self)->loop);
    }
    Py_XDECREF(result);

    Py_DECREF(self);
    PyGILState_Release(gstate);
}
コード例 #18
0
ファイル: pyconcrete_exe.c プロジェクト: holitics/pyconcrete
void execPycContent(PyObject* pyc_content)
{
    PyObject* py_marshal = NULL;
    PyObject* py_marshal_loads = NULL;
    PyObject* pyc_content_wo_magic = NULL;
    PyObject* py_code = NULL;
    PyObject* global = PyDict_New();
    PyObject* local = PyDict_New();
    Py_ssize_t content_size = 0;
    char* content = NULL;
#if PY_MAJOR_VERSION >= 3
    PyObject* main_name = PyUnicode_FromString("__main__");
#else
    PyObject* main_name = PyBytes_FromString("__main__");
#endif

    // load compiled source from .pyc content
    py_marshal = PyImport_ImportModule("marshal");
    py_marshal_loads = PyObject_GetAttrString(py_marshal, "loads");

    content = PyBytes_AS_STRING(pyc_content);
    content_size = PyBytes_Size(pyc_content);

    pyc_content_wo_magic = PyBytes_FromStringAndSize(content+MAGIC_OFFSET, content_size-MAGIC_OFFSET);
    py_code = PyObject_CallFunctionObjArgs(py_marshal_loads, pyc_content_wo_magic, NULL);

    // setup global and exec loaded py_code
    PyDict_SetItemString(global, "__name__", main_name);
    PyDict_SetItemString(global, "__builtins__", PyEval_GetBuiltins());
    PyEval_EvalCode((PyCodeObject*)py_code, global, local);

    Py_DECREF(py_code);
    Py_DECREF(global);
    Py_DECREF(local);
    Py_DECREF(pyc_content_wo_magic);
    Py_DECREF(py_marshal_loads);
    Py_DECREF(py_marshal);
}
コード例 #19
0
ファイル: atom.c プロジェクト: mabragor/ibcl
PyObject * atom(PyObject *obj) {
  PyObject *moddict = NULL;
  PyObject *mod = NULL;
  PyObject *fun = NULL;
  PyObject *res = NULL;

  moddict = PyImport_GetModuleDict();
  if (!moddict) goto error;

  mod = PyMapping_GetItemString(moddict,
  				"toy");
  if (!mod) goto error;
  fprintf(stderr, "Found toy module\n");

  fun = PyObject_GetAttrString(mod,
  			       "atom");
  if (!fun) goto error;
  fprintf(stderr, "Found atom there\n");

  res = PyObject_CallFunctionObjArgs(fun,
				     obj,
  				     NULL);
  if (!res) goto error;
  fprintf(stderr, "Called atom\n");

 success:
  Py_XDECREF(fun);
  Py_XDECREF(mod);
  fprintf(stderr, "Returning from atom\n");
  return res;

 error:
  Py_XDECREF(fun);
  Py_XDECREF(mod);
  Py_XDECREF(res);

  return NULL;
}
コード例 #20
0
ファイル: Scheduler.c プロジェクト: CZ-NIC/dionaea
/* Scheduler scheduler callback */
static double
scheduler_Scheduler(ev_periodic *periodic, double now)
{
    PyGILState_STATE gstate = PyGILState_Ensure();
    double result;
    Scheduler *self = periodic->data;
    PyObject *pynow, *pyresult = NULL;

    pynow = PyFloat_FromDouble(now);
    if (!pynow) {
        self->err_fatal = 1;
        goto error;
    }
    pyresult = PyObject_CallFunctionObjArgs(self->scheduler, self, pynow, NULL);
    if (!pyresult) {
        goto error;
    }
    result = PyFloat_AsDouble(pyresult);
    if (result == -1 && PyErr_Occurred()) {
        goto error;
    }
    if (result < now) {
        PyErr_SetString(Error, "returned value must be >= 'now' param");
        goto error;
    }
    goto finish;

error:
    PyErr_Fetch(&self->err_type, &self->err_value, &self->err_traceback);
    ev_prepare_start(((Watcher *)self)->loop->loop, &self->prepare);
    result = now + 1e30;

finish:
    Py_XDECREF(pyresult);
    Py_XDECREF(pynow);
    PyGILState_Release(gstate);
    return result;
}
コード例 #21
0
ファイル: python-dir.c プロジェクト: bitroniq/bareos
static bRC PyHandlePluginEvent(bpContext *ctx, bDirEvent *event, void *value)
{
   bRC retval = bRC_Error;
   plugin_ctx *p_ctx = (plugin_ctx *)ctx->pContext;
   PyObject *pFunc;

   /*
    * Lookup the handle_plugin_event() function in the python module.
    */
   pFunc = PyDict_GetItemString(p_ctx->pDict, "handle_plugin_event"); /* Borrowed reference */
   if (pFunc && PyCallable_Check(pFunc)) {
      PyObject *pEventType,
               *pRetVal;

      pEventType = PyInt_FromLong(event->eventType);

      pRetVal = PyObject_CallFunctionObjArgs(pFunc, p_ctx->bpContext, pEventType, NULL);
      Py_DECREF(pEventType);

      if (!pRetVal) {
         goto bail_out;
      } else {
         retval = conv_python_retval(pRetVal);
         Py_DECREF(pRetVal);
      }
   } else {
      Dmsg(ctx, dbglvl, "Failed to find function named handle_plugin_event()\n");
   }

   return retval;

bail_out:
   if (PyErr_Occurred()) {
      PyErrorHandler(ctx, M_FATAL);
   }

   return retval;
}
コード例 #22
0
ファイル: py-prettyprint.c プロジェクト: simark/binutils-gdb
static PyObject *
search_pp_list (PyObject *list, PyObject *value)
{
  Py_ssize_t pp_list_size, list_index;

  pp_list_size = PyList_Size (list);
  for (list_index = 0; list_index < pp_list_size; list_index++)
    {
      PyObject *function = PyList_GetItem (list, list_index);
      if (! function)
	return NULL;

      /* Skip if disabled.  */
      if (PyObject_HasAttr (function, gdbpy_enabled_cst))
	{
	  gdbpy_ref<> attr (PyObject_GetAttr (function, gdbpy_enabled_cst));
	  int cmp;

	  if (attr == NULL)
	    return NULL;
	  cmp = PyObject_IsTrue (attr.get ());
	  if (cmp == -1)
	    return NULL;

	  if (!cmp)
	    continue;
	}

      gdbpy_ref<> printer (PyObject_CallFunctionObjArgs (function, value,
							 NULL));
      if (printer == NULL)
	return NULL;
      else if (printer != Py_None)
	return printer.release ();
    }

  Py_RETURN_NONE;
}
コード例 #23
0
ファイル: connection_int.c プロジェクト: psycopg/psycopg2
/* Encode an unicode object into a bytes object in the connection encoding.
 *
 * If no connection or encoding is available, default to utf8
 */
PyObject *
conn_encode(connectionObject *self, PyObject *u)
{
    PyObject *t = NULL;
    PyObject *rv = NULL;

    if (!(self && self->pyencoder)) {
        rv = PyUnicode_AsUTF8String(u);
        goto exit;
    }

    if (!(t = PyObject_CallFunctionObjArgs(self->pyencoder, u, NULL))) {
        goto exit;
    }

    if (!(rv = PyTuple_GetItem(t, 0))) { goto exit; }
    Py_INCREF(rv);

exit:
    Py_XDECREF(t);

    return rv;
}
コード例 #24
0
ファイル: PyService.cpp プロジェクト: mr-kelly/llbc
void pyllbc_Service::HandleFrameCallables(pyllbc_Service::_FrameCallables &callables, bool &usingFlag)
{
    usingFlag = true;
    for (_FrameCallables::iterator it = callables.begin();
         it != callables.end();
         it++)
    {
        PyObject *callable = *it;
        PyObject *ret = PyObject_CallFunctionObjArgs(callable, _pySvc, NULL);
        if (ret)
        {
            Py_DECREF(ret);
        }
        else
        {
            const LLBC_String objDesc = pyllbc_ObjUtil::GetObjStr(callable);
            pyllbc_TransferPyError(LLBC_String().format("When call frame-callable: %s", objDesc.c_str()));
            break;
        }
    }

    this->DestroyFrameCallables(callables, usingFlag);
}
コード例 #25
0
ファイル: session.c プロジェクト: ZenithDK/pyspotify
/* TODO: convert to Py_VaBuildValue based solution so we can support
 *   music_delivery?
 * TODO: could we avoid having to pass session into the python callbacks, or
 *   could we at least store a g_py_session to save us reconstructing it all
 *   the time? Or would that break in unexpected ways if the session gets
 *   modified? Measuring the affect of changing say music_delivery to not
 *   waste time contructing the session would be a good place to start.
 * TODO: could we avoid having to lookup the attr for the callback on every
 *   single callback? Would that break cases where people change the config
 *   later, does that matter?
 */
static void
session_callback(sp_session * session, const char *attr, PyObject *extra)
{
    PyObject *callback, *client, *py_session, *result;
    py_session = Session_FromSpotify(session);
    if (py_session != NULL) {

        client = (PyObject *)sp_session_userdata(session);
        callback = PyObject_GetAttrString(client, attr);

        if (callback != NULL) {
            result = PyObject_CallFunctionObjArgs(callback, py_session, extra, NULL);

            if (result == NULL)
                PyErr_WriteUnraisable(callback);
            else
                Py_DECREF(result);

            Py_DECREF(callback);
        }
        Py_DECREF(py_session);
    }
}
コード例 #26
0
ファイル: signal.c プロジェクト: jppommet/pyuv
static void
on_signal_callback(uv_signal_t *handle, int signum)
{
    PyGILState_STATE gstate = PyGILState_Ensure();
    Signal *self;
    PyObject *result;

    ASSERT(handle);

    self = (Signal *)handle->data;
    ASSERT(self);
    /* Object could go out of scope in the callback, increase refcount to avoid it */
    Py_INCREF(self);

    result = PyObject_CallFunctionObjArgs(self->callback, self, PyInt_FromLong((long)signum), NULL);
    if (result == NULL) {
        handle_uncaught_exception(((Handle *)self)->loop);
    }
    Py_XDECREF(result);

    Py_DECREF(self);
    PyGILState_Release(gstate);
}
コード例 #27
0
ファイル: edgeseqobject.c プロジェクト: bravery/python-igraph
/**
 * \ingroup python_interface_edgqseq
 * \brief Selects a single edge from the edge sequence based on some criteria
 */
PyObject* igraphmodule_EdgeSeq_find(igraphmodule_EdgeSeqObject *self, PyObject *args) {
  PyObject *item;
  long int i, n;

  if (!PyArg_ParseTuple(args, "O", &item))
    return NULL;

  if (PyCallable_Check(item)) {
    /* Call the callable for every edge in the current sequence and return
     * the first one for which it evaluates to True */
    n = PySequence_Size((PyObject*)self);
    for (i=0; i<n; i++) {
      PyObject *edge = PySequence_GetItem((PyObject*)self, i);
      PyObject *call_result;
      if (edge == 0)
        return NULL;
      call_result = PyObject_CallFunctionObjArgs(item, edge, NULL);
      if (call_result == 0) {
        Py_DECREF(edge);
        return NULL;
      }
      if (PyObject_IsTrue(call_result)) {
        Py_DECREF(call_result);
        return edge;  /* reference passed to caller */
      }
      Py_DECREF(call_result);
      Py_DECREF(edge);
    }
  } else if (PyInt_Check(item)) {
    /* Integers are interpreted as indices on the edge set and NOT on the
     * original, untouched edge sequence of the graph */
    return PySequence_GetItem((PyObject*)self, PyInt_AsLong(item));
  }

  PyErr_SetString(PyExc_IndexError, "no such edge");
  return NULL;
}
コード例 #28
0
/* TODO: may have been changed to BORROWED */
RAISES PyObject *
psyco_set_error(PyObject *exc, cursorObject *curs, const char *msg)
{
    PyObject *pymsg;
    PyObject *err = NULL;
    connectionObject *conn = NULL;

    if (curs) {
        conn = ((cursorObject *)curs)->conn;
    }

    if ((pymsg = conn_text_from_chars(conn, msg))) {
        err = PyObject_CallFunctionObjArgs(exc, pymsg, NULL);
        Py_DECREF(pymsg);
    }
    else {
        /* what's better than an error in an error handler in the morning?
         * Anyway, some error was set, refcount is ok... get outta here. */
        return NULL;
    }

    if (err && PyObject_TypeCheck(err, &errorType)) {
        errorObject *perr = (errorObject *)err;
        if (curs) {
            Py_CLEAR(perr->cursor);
            Py_INCREF(curs);
            perr->cursor = curs;
        }
    }

    if (err) {
        PyErr_SetObject(exc, err);
        Py_DECREF(err);
    }

    return err;
}
コード例 #29
0
ファイル: builder.c プロジェクト: abed-hawa/amara
static ExpatStatus
builder_Comment(void *userState, PyObject *data)
{
  ParserState *state = (ParserState *)userState;
  NodeObject *node;

#ifdef DEBUG_PARSER
  fprintf(stderr, "--- builder_Comment(data=");
  PyObject_Print(data, stderr, 0);
  fprintf(stderr, ")\n");
#endif

  if (state->comment_factory) {
    node = (NodeObject *)PyObject_CallFunctionObjArgs(state->comment_factory,
                                                      data, NULL);
    if (node == NULL)
      return EXPAT_STATUS_ERROR;
    if (!Text_Check(node)) {
      PyErr_Format(PyExc_TypeError,
                   "xml_comment_factory should return comment, not %s",
                   node->ob_type->tp_name);
      Py_DECREF(node);
      return EXPAT_STATUS_ERROR;
    }
  } else {
    node = (NodeObject *)Comment_New(data);
    if (node == NULL)
      return EXPAT_STATUS_ERROR;
  }

  /* ParserState_AddNode steals the reference to the new node */
  if (ParserState_AddNode(state, node) < 0) {
    Py_DECREF(node);
    return EXPAT_STATUS_ERROR;
  }
  return EXPAT_STATUS_OK;
}
コード例 #30
0
static PyObject *
verifying_changed(verify *self, PyObject *ignored)
{
  PyObject *t, *ro;

  verifying_clear(self);

  t = PyObject_GetAttr(OBJECT(self), str_registry);
  if (t == NULL)
    return NULL;
  ro = PyObject_GetAttr(t, strro);
  Py_DECREF(t);
  if (ro == NULL)
    return NULL;

  t = PyObject_CallFunctionObjArgs(OBJECT(&PyTuple_Type), ro, NULL);
  Py_DECREF(ro);
  if (t == NULL)
    return NULL;

  ro = PyTuple_GetSlice(t, 1, PyTuple_GET_SIZE(t));
  Py_DECREF(t);
  if (ro == NULL)
    return NULL;

  self->_verify_generations = _generations_tuple(ro);
  if (self->_verify_generations == NULL)
    {
      Py_DECREF(ro);
      return NULL;
    }

  self->_verify_ro = ro;

  Py_INCREF(Py_None);
  return Py_None;
}