当前位置: 首页>>代码示例>>C++>>正文


C++ PyGILState_Ensure函数代码示例

本文整理汇总了C++中PyGILState_Ensure函数的典型用法代码示例。如果您正苦于以下问题:C++ PyGILState_Ensure函数的具体用法?C++ PyGILState_Ensure怎么用?C++ PyGILState_Ensure使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了PyGILState_Ensure函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。

示例1: on_udp_read

static void
on_udp_read(uv_udp_t* handle, int nread, uv_buf_t buf, struct sockaddr* addr, unsigned flags)
{
    PyGILState_STATE gstate = PyGILState_Ensure();
    char ip[INET6_ADDRSTRLEN];
    struct sockaddr_in addr4;
    struct sockaddr_in6 addr6;
    uv_err_t err;
    UDP *self;
    PyObject *result, *address_tuple, *data, *py_errorno;

    ASSERT(handle);
    ASSERT(flags == 0);

    self = (UDP *)handle->data;
    ASSERT(self);

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

    if (nread == 0) {
        goto done;
    }

    if (nread > 0) {
        ASSERT(addr);
        if (addr->sa_family == AF_INET) {
            addr4 = *(struct sockaddr_in*)addr;
            uv_ip4_name(&addr4, ip, INET_ADDRSTRLEN);
            address_tuple = Py_BuildValue("(si)", ip, ntohs(addr4.sin_port));
        } else {
            addr6 = *(struct sockaddr_in6*)addr;
            uv_ip6_name(&addr6, ip, INET6_ADDRSTRLEN);
            address_tuple = Py_BuildValue("(si)", ip, ntohs(addr6.sin6_port));
        }
        data = PyBytes_FromStringAndSize(buf.base, nread);
        py_errorno = Py_None;
        Py_INCREF(Py_None);
    } else if (nread < 0) {
        address_tuple = Py_None;
        Py_INCREF(Py_None);
        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, address_tuple, data, py_errorno, NULL);
    if (result == NULL) {
        handle_uncaught_exception(((Handle *)self)->loop);
    }
    Py_XDECREF(result);
    Py_DECREF(address_tuple);
    Py_DECREF(data);
    Py_DECREF(py_errorno);

done:
    /* In case of error libuv may not call alloc_cb */
    if (buf.base != NULL) {
        PyMem_Free(buf.base);
    }

    Py_DECREF(self);
    PyGILState_Release(gstate);
}
开发者ID:jppommet,项目名称:pyuv,代码行数:65,代码来源:udp.c

示例2: pysmraw_file_object_io_handle_get_size

/* Retrieves the file size
 * Returns 1 if successful or -1 on error
 */
int pysmraw_file_object_io_handle_get_size(
     pysmraw_file_object_io_handle_t *file_object_io_handle,
     size64_t *size,
     libcerror_error_t **error )
{
	PyObject *method_name      = NULL;
	static char *function      = "pysmraw_file_object_io_handle_get_size";
	PyGILState_STATE gil_state = 0;
	off64_t current_offset     = 0;
	int result                 = 0;

	if( file_object_io_handle == NULL )
	{
		libcerror_error_set(
		 error,
		 LIBCERROR_ERROR_DOMAIN_ARGUMENTS,
		 LIBCERROR_ARGUMENT_ERROR_INVALID_VALUE,
		 "%s: invalid file object IO handle.",
		 function );

		return( -1 );
	}
	if( file_object_io_handle->file_object == NULL )
	{
		libcerror_error_set(
		 error,
		 LIBCERROR_ERROR_DOMAIN_RUNTIME,
		 LIBCERROR_RUNTIME_ERROR_VALUE_MISSING,
		 "%s: invalid file object IO handle - missing file object.",
		 function );

		return( -1 );
	}
	gil_state = PyGILState_Ensure();

#if PY_MAJOR_VERSION >= 3
	method_name = PyUnicode_FromString(
	               "get_size" );
#else
	method_name = PyString_FromString(
	               "get_size" );
#endif
	PyErr_Clear();

	/* Determine if the file object has the get_size method
	 */
	result = PyObject_HasAttr(
	          file_object_io_handle->file_object,
	          method_name );

	if( result != 0 )
	{
		if( pysmraw_file_object_get_size(
		     file_object_io_handle->file_object,
		     size,
		     error ) != 1 )
		{
			libcerror_error_set(
			 error,
			 LIBCERROR_ERROR_DOMAIN_RUNTIME,
			 LIBCERROR_RUNTIME_ERROR_GET_FAILED,
			 "%s: unable to retrieve size of file object.",
			 function );

			goto on_error;
		}
	}
	else
	{
		if( pysmraw_file_object_get_offset(
		     file_object_io_handle->file_object,
		     &current_offset,
		     error ) != 1 )
		{
			libcerror_error_set(
			 error,
			 LIBCERROR_ERROR_DOMAIN_RUNTIME,
			 LIBCERROR_RUNTIME_ERROR_GET_FAILED,
			 "%s: unable to retrieve current offset in file object.",
			 function );

			goto on_error;
		}
		if( pysmraw_file_object_seek_offset(
		     file_object_io_handle->file_object,
		     0,
		     SEEK_END,
		     error ) != 1 )
		{
			libcerror_error_set(
			 error,
			 LIBCERROR_ERROR_DOMAIN_IO,
			 LIBCERROR_IO_ERROR_SEEK_FAILED,
			 "%s: unable to seek end of file object.",
			 function );

			goto on_error;
//.........这里部分代码省略.........
开发者ID:libyal,项目名称:libsmraw,代码行数:101,代码来源:pysmraw_file_object_io_handle.c

示例3: DoPy3Command

/*
 * External interface
 */
    static void
DoPy3Command(exarg_T *eap, const char *cmd)
{
#if defined(MACOS) && !defined(MACOS_X_UNIX)
    GrafPtr		oldPort;
#endif
#if defined(HAVE_LOCALE_H) || defined(X_LOCALE)
    char		*saved_locale;
#endif
    PyObject		*cmdstr;
    PyObject		*cmdbytes;

#if defined(MACOS) && !defined(MACOS_X_UNIX)
    GetPort(&oldPort);
    /* Check if the Python library is available */
    if ((Ptr)PyMac_Initialize == (Ptr)kUnresolvedCFragSymbolAddress)
	goto theend;
#endif
    if (Python3_Init())
	goto theend;

    RangeStart = eap->line1;
    RangeEnd = eap->line2;
    Python_Release_Vim();	    /* leave vim */

#if defined(HAVE_LOCALE_H) || defined(X_LOCALE)
    /* Python only works properly when the LC_NUMERIC locale is "C". */
    saved_locale = setlocale(LC_NUMERIC, NULL);
    if (saved_locale == NULL || STRCMP(saved_locale, "C") == 0)
	saved_locale = NULL;
    else
    {
	/* Need to make a copy, value may change when setting new locale. */
	saved_locale = (char *)vim_strsave((char_u *)saved_locale);
	(void)setlocale(LC_NUMERIC, "C");
    }
#endif

    pygilstate = PyGILState_Ensure();

    /* PyRun_SimpleString expects a UTF-8 string. Wrong encoding may cause
     * SyntaxError (unicode error). */
    cmdstr = PyUnicode_Decode(cmd, strlen(cmd),
					(char *)ENC_OPT, CODEC_ERROR_HANDLER);
    cmdbytes = PyUnicode_AsEncodedString(cmdstr, "utf-8", CODEC_ERROR_HANDLER);
    Py_XDECREF(cmdstr);
    PyRun_SimpleString(PyBytes_AsString(cmdbytes));
    Py_XDECREF(cmdbytes);

    PyGILState_Release(pygilstate);

#if defined(HAVE_LOCALE_H) || defined(X_LOCALE)
    if (saved_locale != NULL)
    {
	(void)setlocale(LC_NUMERIC, saved_locale);
	vim_free(saved_locale);
    }
#endif

    Python_Lock_Vim();		    /* enter vim */
    PythonIO_Flush();
#if defined(MACOS) && !defined(MACOS_X_UNIX)
    SetPort(oldPort);
#endif

theend:
    return;	    /* keeps lint happy */
}
开发者ID:Bitesher,项目名称:Vim,代码行数:71,代码来源:if_python3.c

示例4: _CallPythonObject

/******************************************************************************
 *
 * Call the python object with all arguments
 *
 */
static void _CallPythonObject(void *mem,
                              ffi_type *restype,
                              SETFUNC setfunc,
                              PyObject *callable,
                              PyObject *converters,
                              void **pArgs)
{
    int i;
    PyObject *result;
    PyObject *arglist = NULL;
    int nArgs;
#ifdef WITH_THREAD
    PyGILState_STATE state = PyGILState_Ensure();
#endif

    nArgs = PySequence_Length(converters);
    /* Hm. What to return in case of error?
       For COM, 0xFFFFFFFF seems better than 0.
    */
    if (nArgs < 0) {
        PrintError("BUG: PySequence_Length");
        goto Done;
    }

    arglist = PyTuple_New(nArgs);
    if (!arglist) {
        PrintError("PyTuple_New()");
        goto Done;
    }
    for (i = 0; i < nArgs; ++i) {
        /* Note: new reference! */
        PyObject *cnv = PySequence_GetItem(converters, i);
        StgDictObject *dict;
        if (cnv)
            dict = PyType_stgdict(cnv);
        else {
            PrintError("Getting argument converter %d\n", i);
            goto Done;
        }

        if (dict && dict->getfunc && !IsSimpleSubType(cnv)) {
            PyObject *v = dict->getfunc(*pArgs, dict->size);
            if (!v) {
                PrintError("create argument %d:\n", i);
                Py_DECREF(cnv);
                goto Done;
            }
            PyTuple_SET_ITEM(arglist, i, v);
            /* XXX XXX XX
               We have the problem that c_byte or c_short have dict->size of
               1 resp. 4, but these parameters are pushed as sizeof(int) bytes.
               BTW, the same problem occurrs when they are pushed as parameters
            */
        } else if (dict) {
            /* Hm, shouldn't we use CData_AtAddress() or something like that instead? */
            CDataObject *obj = (CDataObject *)PyObject_CallFunctionObjArgs(cnv, NULL);
            if (!obj) {
                PrintError("create argument %d:\n", i);
                Py_DECREF(cnv);
                goto Done;
            }
            if (!CDataObject_Check(obj)) {
                Py_DECREF(obj);
                Py_DECREF(cnv);
                PrintError("unexpected result of create argument %d:\n", i);
                goto Done;
            }
            memcpy(obj->b_ptr, *pArgs, dict->size);
            PyTuple_SET_ITEM(arglist, i, (PyObject *)obj);
#ifdef MS_WIN32
            TryAddRef(dict, obj);
#endif
        } else {
            PyErr_SetString(PyExc_TypeError,
                            "cannot build parameter");
            PrintError("Parsing argument %d\n", i);
            Py_DECREF(cnv);
            goto Done;
        }
        Py_DECREF(cnv);
        /* XXX error handling! */
        pArgs++;
    }

#define CHECK(what, x) \
if (x == NULL) _AddTraceback(what, __FILE__, __LINE__ - 1), PyErr_Print()

    result = PyObject_CallObject(callable, arglist);
    CHECK("'calling callback function'", result);
    if ((restype != &ffi_type_void) && result) {
        PyObject *keep;
        assert(setfunc);
#ifdef WORDS_BIGENDIAN
        /* See the corresponding code in callproc.c, around line 961 */
        if (restype->type != FFI_TYPE_FLOAT && restype->size < sizeof(ffi_arg))
//.........这里部分代码省略.........
开发者ID:swolchok,项目名称:dspython,代码行数:101,代码来源:callbacks.c

示例5: gil_gevent_get

static void gil_gevent_get() {
	pthread_setspecific(up.upt_gil_key, (void *) PyGILState_Ensure());
}
开发者ID:RyuaNerin,项目名称:uwsgi,代码行数:3,代码来源:gevent.c

示例6: PyScopedGIL

 PyScopedGIL() {
     gstate = PyGILState_Ensure();
 }
开发者ID:renrut,项目名称:qstream,代码行数:3,代码来源:PyThreading.hpp

示例7: pythonmod_init

int pythonmod_init(struct module_env* env, int id)
{
   /* Initialize module */
   FILE* script_py = NULL;
   PyObject* py_cfg, *res;
   PyGILState_STATE gil;
   struct pythonmod_env* pe = (struct pythonmod_env*)calloc(1, sizeof(struct pythonmod_env));
   if (!pe) 
   {
      log_err("pythonmod: malloc failure");
      return 0;
   }

   env->modinfo[id] = (void*) pe;

   /* Initialize module */
   pe->fname = env->cfg->python_script;
   if(pe->fname==NULL || pe->fname[0]==0) {
      log_err("pythonmod: no script given.");
      return 0;
   }

   /* Initialize Python libraries */
   if (!Py_IsInitialized()) 
   {
      Py_SetProgramName("unbound");
      Py_NoSiteFlag = 1;
      Py_Initialize();
      PyEval_InitThreads();
      SWIG_init();
      pe->mainthr = PyEval_SaveThread();
   }

   gil = PyGILState_Ensure();

   /* Initialize Python */
   PyRun_SimpleString("import sys \n");
   PyRun_SimpleString("sys.path.append('.') \n");
   if(env->cfg->directory && env->cfg->directory[0]) {
   	char wdir[1524];
   	snprintf(wdir, sizeof(wdir), "sys.path.append('%s') \n",
		env->cfg->directory);
   	PyRun_SimpleString(wdir);
   }
   PyRun_SimpleString("sys.path.append('"RUN_DIR"') \n");
   PyRun_SimpleString("sys.path.append('"SHARE_DIR"') \n");
   PyRun_SimpleString("import distutils.sysconfig \n");
   PyRun_SimpleString("sys.path.append(distutils.sysconfig.get_python_lib(1,0)) \n");
   if (PyRun_SimpleString("from unboundmodule import *\n") < 0)
   {
      log_err("pythonmod: cannot initialize core module: unboundmodule.py"); 
      PyGILState_Release(gil);
      return 0;
   }

   /* Check Python file load */
   if ((script_py = fopen(pe->fname, "r")) == NULL) 
   {
      log_err("pythonmod: can't open file %s for reading", pe->fname);
      PyGILState_Release(gil);
      return 0;
   }

   /* Load file */
   pe->module = PyImport_AddModule("__main__");
   pe->dict = PyModule_GetDict(pe->module);
   pe->data = Py_None;
   Py_INCREF(pe->data);
   PyModule_AddObject(pe->module, "mod_env", pe->data);

   /* TODO: deallocation of pe->... if an error occurs */
  
   if (PyRun_SimpleFile(script_py, pe->fname) < 0) 
   {
      log_err("pythonmod: can't parse Python script %s", pe->fname);
      PyGILState_Release(gil);
      return 0;
   }

   fclose(script_py);

   if ((pe->func_init = PyDict_GetItemString(pe->dict, "init")) == NULL) 
   {
      log_err("pythonmod: function init is missing in %s", pe->fname);
      PyGILState_Release(gil);
      return 0;
   }
   if ((pe->func_deinit = PyDict_GetItemString(pe->dict, "deinit")) == NULL) 
   {
      log_err("pythonmod: function deinit is missing in %s", pe->fname);
      PyGILState_Release(gil);
      return 0;
   }
   if ((pe->func_operate = PyDict_GetItemString(pe->dict, "operate")) == NULL) 
   {
      log_err("pythonmod: function operate is missing in %s", pe->fname);
      PyGILState_Release(gil);
      return 0;
   }
   if ((pe->func_inform = PyDict_GetItemString(pe->dict, "inform_super")) == NULL) 
//.........这里部分代码省略.........
开发者ID:mir-ror,项目名称:unbound,代码行数:101,代码来源:pythonmod.c

示例8: nameinfo_cb

static void
nameinfo_cb(void *arg, int status, int timeouts, char *node, char *service)
{
    PyGILState_STATE gstate = PyGILState_Ensure();
    ares_cb_data_t *data;
    DNSResolver *self;
    PyObject *callback, *errorno, *dns_node, *dns_service, *dns_result, *result;

    ASSERT(arg);

    data = (ares_cb_data_t*)arg;
    self = data->resolver;
    callback = data->cb;

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

    if (status != ARES_SUCCESS) {
        errorno = PyInt_FromLong((long)status);
        dns_result = Py_None;
        Py_INCREF(Py_None);
        goto callback;
    }

    dns_result = PyTuple_New(2);
    if (!dns_result) {
        PyErr_NoMemory();
        PyErr_WriteUnraisable(Py_None);
        errorno = PyInt_FromLong((long)ARES_ENOMEM);
        dns_result = Py_None;
        Py_INCREF(Py_None);
        goto callback;
    }

    dns_node = PyString_FromString(node);
    if (service) {
        dns_service = PyString_FromString(service);
    } else {
        dns_service = Py_None;
        Py_INCREF(Py_None);
    }

    PyTuple_SET_ITEM(dns_result, 0, dns_node);
    PyTuple_SET_ITEM(dns_result, 1, dns_service);
    errorno = Py_None;
    Py_INCREF(Py_None);

callback:
    result = PyObject_CallFunctionObjArgs(callback, self, dns_result, errorno, NULL);
    if (result == NULL) {
        PyErr_WriteUnraisable(callback);
    }
    Py_XDECREF(result);

    Py_DECREF(callback);
    PyMem_Free(data);

    Py_DECREF(self);
    PyGILState_Release(gstate);
}
开发者ID:ikeikeikeike,项目名称:pyuv,代码行数:61,代码来源:dns.c

示例9: host_cb

static void
host_cb(void *arg, int status, int timeouts, struct hostent *hostent)
{
    PyGILState_STATE gstate = PyGILState_Ensure();
    char ip[INET6_ADDRSTRLEN];
    char **ptr;
    ares_cb_data_t *data;
    DNSResolver *self;
    PyObject *callback, *dns_name, *errorno, *dns_aliases, *dns_addrlist, *dns_result, *tmp, *result;

    ASSERT(arg);

    data = (ares_cb_data_t*)arg;
    self = data->resolver;
    callback = data->cb;

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

    if (status != ARES_SUCCESS) {
        errorno = PyInt_FromLong((long)status);
        dns_result = Py_None;
        Py_INCREF(Py_None);
        goto callback;
    }

    dns_aliases = PyList_New(0);
    dns_addrlist = PyList_New(0);
    dns_result = PyTuple_New(3);

    if (!(dns_aliases && dns_addrlist && dns_result)) {
        PyErr_NoMemory();
        PyErr_WriteUnraisable(Py_None);
        Py_XDECREF(dns_aliases);
        Py_XDECREF(dns_addrlist);
        Py_XDECREF(dns_result);
        errorno = PyInt_FromLong((long)ARES_ENOMEM);
        dns_result = Py_None;
        Py_INCREF(Py_None);
        goto callback;
    }

    for (ptr = hostent->h_aliases; *ptr != NULL; ptr++) {
        if (*ptr != hostent->h_name && strcmp(*ptr, hostent->h_name)) {
            tmp = PyString_FromString(*ptr);
            if (tmp == NULL) {
                break;
            }
            PyList_Append(dns_aliases, tmp);
            Py_DECREF(tmp);
        }
    }
    for (ptr = hostent->h_addr_list; *ptr != NULL; ptr++) {
        if (hostent->h_addrtype == AF_INET) {
            uv_inet_ntop(AF_INET, *ptr, ip, INET_ADDRSTRLEN);
            tmp = PyString_FromString(ip);
        } else if (hostent->h_addrtype == AF_INET6) {
            uv_inet_ntop(AF_INET6, *ptr, ip, INET6_ADDRSTRLEN);
            tmp = PyString_FromString(ip);
        } else {
            continue;
        }
        if (tmp == NULL) {
            break;
        }
        PyList_Append(dns_addrlist, tmp);
        Py_DECREF(tmp);
    }
    dns_name = PyString_FromString(hostent->h_name);

    PyTuple_SET_ITEM(dns_result, 0, dns_name);
    PyTuple_SET_ITEM(dns_result, 1, dns_aliases);
    PyTuple_SET_ITEM(dns_result, 2, dns_addrlist);
    errorno = Py_None;
    Py_INCREF(Py_None);

callback:
    result = PyObject_CallFunctionObjArgs(callback, self, dns_result, errorno, NULL);
    if (result == NULL) {
        PyErr_WriteUnraisable(callback);
    }
    Py_XDECREF(result);

    Py_DECREF(callback);
    PyMem_Free(data);

    Py_DECREF(self);
    PyGILState_Release(gstate);
}
开发者ID:ikeikeikeike,项目名称:pyuv,代码行数:90,代码来源:dns.c

示例10: kbdint_response_callback

static void kbdint_response_callback(const char* name, int name_len,
                                     const char* instruction, int instruction_len,
                                     int num_prompts,
                                     const LIBSSH2_USERAUTH_KBDINT_PROMPT* prompts,
                                     LIBSSH2_USERAUTH_KBDINT_RESPONSE* responses,
                                     void **abstract)
{
	PyGILState_STATE gstate = PyGILState_Ensure();
	PyObject *callback = ((SSH2_SessionObj*) *abstract)->cb_kbdint_response;
	PyObject *lprompts = PyList_New(num_prompts);
	PyObject *rv = NULL;
	PyObject *it = NULL;
	int i;

	for (i = 0; i < num_prompts; i++) {
		PyList_SET_ITEM(lprompts, i, Py_BuildValue("(s#O)", prompts[i].text,
		                                                    prompts[i].length,
		                                                    prompts[i].echo ? Py_True : Py_False));
	}

	rv = PyObject_CallFunction(callback, "s#s#O", name, name_len, instruction, instruction_len, lprompts);
	Py_DECREF(lprompts);

	if (rv == NULL)
		goto failure;

	it = PyObject_GetIter(rv);
	Py_DECREF(rv);

	if (it == NULL)
		goto failure;

	for (i = 0; i < num_prompts; i++) {
		PyObject *item = PyIter_Next(it);
		char *s;
		Py_ssize_t length;
		int ret;

		if (item == NULL) {
			Py_DECREF(it);

			if (!PyErr_Occurred()) {
				PyErr_Format(PyExc_ValueError, "callback returned %i reponse(s), "
				                               "but %i prompt(s) were given", i, num_prompts);
			}

			goto failure;
		}

#if PY_MAJOR_VERSION < 3
		ret = PyString_AsStringAndSize(item, &s, &length);
#else
		{
			PyObject *enc;

			if ((enc = PyUnicode_AsEncodedString(item, NULL, "strict")) == NULL) {
				Py_DECREF(item);
				Py_DECREF(it);

				goto failure;
			}

			ret = PyBytes_AsStringAndSize(enc, &s, &length);
			Py_DECREF(enc);
		}
#endif
		Py_DECREF(item);

		if (ret == -1) {
			Py_DECREF(it);
			goto failure;
		}

		responses[i].text = strndup(s, length);
		responses[i].length = length;
	}

	Py_DECREF(it);
	goto exit;

failure:
	PyErr_WriteUnraisable(callback);
exit:
	PyGILState_Release(gstate);
}
开发者ID:andrevmatos,项目名称:ssh4py,代码行数:85,代码来源:session.c

示例11: TAKE_GIL

PyGILState_STATE TAKE_GIL(void)
{
    PyGILState_STATE state = PyGILState_Ensure();
    takes ++;
    return state;
}
开发者ID:TC01,项目名称:cocotb,代码行数:6,代码来源:simulatormodule.c

示例12: OutputDebugString

//-------------------------------------------------------------------------
	P_GIL::P_GIL() {
		if (!Py_IsInitialized()) {
			OutputDebugString("Grabbing GIL from uninitilized Python?!");
		}
		this->state = PyGILState_Ensure();
	}
开发者ID:AmesianX,项目名称:pydetour,代码行数:7,代码来源:CPPPython.cpp

示例13: gil_guard_t

	gil_guard_t()
		: gstate(PyGILState_Ensure())
		, is_released(false)
	{
	}
开发者ID:yandex,项目名称:libmastermind,代码行数:5,代码来源:main.cpp

示例14: _pygi_closure_handle

void
_pygi_closure_handle (ffi_cif *cif,
                      void    *result,
                      void   **args,
                      void    *data)
{
    PyGILState_STATE state;
    PyGICClosure *closure = data;
    gint n_args, i;
    GIArgInfo  *arg_info;
    GIDirection arg_direction;
    GITypeInfo *arg_type;
    GITransfer arg_transfer;
    GITypeTag  arg_tag;
    GITypeTag  return_tag;
    GITransfer return_transfer;
    GITypeInfo *return_type;
    PyObject *retval;
    PyObject *py_args;
    PyObject *pyarg;
    gint n_in_args, n_out_args;


    /* Lock the GIL as we are coming into this code without the lock and we
      may be executing python code */
    state = PyGILState_Ensure();

    return_type = g_callable_info_get_return_type(closure->info);
    return_tag = g_type_info_get_tag(return_type);
    return_transfer = g_callable_info_get_caller_owns(closure->info);

    n_args = g_callable_info_get_n_args (closure->info);

    py_args = PyTuple_New(n_args);
    if (py_args == NULL) {
        PyErr_Clear();
        goto end;
    }

    n_in_args = 0;

    for (i = 0; i < n_args; i++) {
        arg_info = g_callable_info_get_arg (closure->info, i);
        arg_type = g_arg_info_get_type (arg_info);
        arg_transfer = g_arg_info_get_ownership_transfer(arg_info);
        arg_tag = g_type_info_get_tag(arg_type);
        arg_direction = g_arg_info_get_direction(arg_info);
        switch (arg_tag) {
        case GI_TYPE_TAG_VOID:
        {
            if (g_type_info_is_pointer(arg_type)) {
                if (PyTuple_SetItem(py_args, n_in_args, closure->user_data) != 0) {
                    PyErr_Clear();
                    goto end;
                }
                n_in_args++;
                continue;
            }
        }
        case GI_TYPE_TAG_ERROR:
        {
            continue;
        }
        default:
        {
            pyarg = _pygi_argument_to_object (args[i],
                                              arg_type,
                                              arg_transfer);

            if(PyTuple_SetItem(py_args, n_in_args, pyarg) != 0) {
                PyErr_Clear();
                goto end;
            }
            n_in_args++;
            g_base_info_unref((GIBaseInfo*)arg_info);
            g_base_info_unref((GIBaseInfo*)arg_type);
        }
        }

    }

    if(_PyTuple_Resize (&py_args, n_in_args) != 0) {
        PyErr_Clear();
        goto end;
    }

    retval = PyObject_CallObject((PyObject *)closure->function, py_args);

    Py_DECREF(py_args);

    if (retval == NULL) {
        goto end;
    }

    *(GArgument*)result = _pygi_argument_from_object(retval, return_type, return_transfer);

end:
    g_base_info_unref((GIBaseInfo*)return_type);

    PyGILState_Release(state);
//.........这里部分代码省略.........
开发者ID:ZachGoldberg,项目名称:pygi,代码行数:101,代码来源:pygi-closure.c

示例15: on_message

// get spectrum messages and delay them
static gboolean on_message(GstBus *bus, GstMessage *message, gpointer data)
{
	base *base_object = data;
	GstElement *spectrum = GST_ELEMENT(base_object->spectrum_element->obj);
	gst_object_ref(spectrum);

	GstElement *message_element = GST_ELEMENT(GST_MESSAGE_SRC(message));
	gst_object_ref(message_element);

	if (message_element == spectrum)
	{
		GstClockTime waittime = GST_CLOCK_TIME_NONE;
		const GstStructure *message_structure = gst_message_get_structure(message);

		// determine waittime
		GstClockTime timestamp, duration;

		if (
			   gst_structure_get_clock_time(message_structure, "running-time", &timestamp)
			&& gst_structure_get_clock_time(message_structure, "duration", &duration)
		)
		{
			/* wait for middle of buffer */
			waittime = timestamp + duration/2;
		}
		else if (gst_structure_get_clock_time(message_structure, "endtime", &timestamp))
		{
			waittime = timestamp;
		}

		// delay message
		if (GST_CLOCK_TIME_IS_VALID(waittime))
		{
			GstClockTime basetime = gst_element_get_base_time(spectrum);
			GstClockID clock_id = gst_clock_new_single_shot_id(base_object->sync_clock, basetime+waittime);
			spectrum_message *mess = g_malloc(sizeof(spectrum_message));

			// set bands and threshold
			g_object_get(message_element, "bands", &(mess->bands), "threshold", &(mess->threshold), NULL);

			// set start and duration
			GstClockTime streamtime, duration;
			gst_structure_get_clock_time(message_structure, "stream-time", &streamtime);
			gst_structure_get_clock_time(message_structure, "duration", &duration);

			mess->start = (gfloat)streamtime / GST_SECOND;
			mess->duration = (gfloat)duration / GST_SECOND;

			// set rate
			GstPad *sink = gst_element_get_static_pad(GST_ELEMENT(base_object->spectrum_element->obj), "sink");
			GstCaps *caps = gst_pad_get_negotiated_caps(sink);
			gst_object_unref(sink);

			GstStructure *caps_structure = gst_caps_get_structure(caps, 0);
			gst_structure_get_int(caps_structure, "rate", &(mess->rate));
			gst_caps_unref(caps);

			// set magnitudes
			const GValue *list = gst_structure_get_value(message_structure, "magnitude");

			PyGILState_STATE gstate = PyGILState_Ensure();

			int i;
			mess->magnitudes = PyList_New(mess->bands);
			for (i=0; i < (mess->bands); i++)
			{
				const GValue *value = gst_value_list_get_value(list, i);
				gfloat f = g_value_get_float(value);
				PyList_SetItem(mess->magnitudes, i, Py_BuildValue("f", f));
			}

			PyGILState_Release(gstate);

			// set gobj
			GObject *gobj = (base_object->gobj).obj;
			g_assert(gobj != NULL);
			g_object_ref(gobj);
			mess->gobj = gobj;

			// delay message
			gst_clock_id_wait_async(clock_id, delayed_spectrum_update, mess);

			gst_clock_id_unref(clock_id);
		}
	}

	gst_object_unref(spectrum);
	gst_object_unref(message_element);

	return TRUE;
}
开发者ID:Leberwurscht,项目名称:Python-Guitar-Transcription-Aid,代码行数:92,代码来源:visualizercontrolbase.c


注:本文中的PyGILState_Ensure函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。