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


C++ PyInt_Check函数代码示例

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


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

示例1: SPI_xfer

static PyObject *
SPI_xfer(SPI *self, PyObject *args)
{
	uint8_t ii, len;
	int status;
	int delay = -1;
	//uint8_t ret = 0;
	PyObject *list;
	struct spi_ioc_transfer *xferptr;
	uint8_t *txbuf, *rxbuf;

	if (!PyArg_ParseTuple(args, "O|i:msg", &list, &delay))
		return NULL;

	if (!PyList_Check(list)) {
		PyErr_SetString(PyExc_TypeError, wrmsg);
		return NULL;
	}

	if ((len = PyList_GET_SIZE(list)) > MAXMSGLEN) {
		PyErr_SetString(PyExc_OverflowError, wrmsg);
		return NULL;
	}

	if (delay == -1) {
		delay = 0;
	}

	xferptr = (struct spi_ioc_transfer*) malloc(sizeof(struct spi_ioc_transfer) * len);
	txbuf = malloc(sizeof(__u8) * len);
	rxbuf = malloc(sizeof(__u8) * len);

	for (ii = 0; ii < len; ii++) {
		PyObject *val = PyList_GET_ITEM(list, ii);
		if (!PyInt_Check(val)) {
			PyErr_SetString(PyExc_TypeError, wrmsg);
			return NULL;
		}
		txbuf[ii] = (__u8)PyInt_AS_LONG(val);
		xferptr[ii].tx_buf = (unsigned long)&txbuf[ii];
		xferptr[ii].rx_buf = (unsigned long)&rxbuf[ii];
		xferptr[ii].len = 1;
		xferptr[ii].delay_usecs = delay;
		xferptr[ii].speed_hz = 0;      
		xferptr[ii].bits_per_word = 0;
	}

	status = ioctl(self->fd, SPI_IOC_MESSAGE(len), xferptr);
	if (status < 0) {
		PyErr_SetFromErrno(PyExc_IOError);
		return NULL;
	}

	for (ii = 0; ii < len; ii++) {
		PyObject *val = Py_BuildValue("l", (long)rxbuf[ii]);
		PyList_SET_ITEM(list, ii, val);
	}

	// WA:
	// in CS_HIGH mode CS isn't pulled to low after transfer, but after read
	// reading 0 bytes doesnt matter but brings cs down
	status = read(self->fd, &rxbuf[0], 0);

	free(txbuf);
	free(rxbuf);
	free(xferptr);

	Py_INCREF(list);
	return list;
}
开发者ID:Aridono,项目名称:adafruit-beaglebone-io-python,代码行数:70,代码来源:spimodule.c

示例2: PyArray_PyIntAsIntp

/*NUMPY_API*/
NPY_NO_EXPORT intp
PyArray_PyIntAsIntp(PyObject *o)
{
    longlong long_value = -1;
    PyObject *obj;
    static char *msg = "an integer is required";
    PyObject *arr;
    PyArray_Descr *descr;
    intp ret;

    if (!o) {
        PyErr_SetString(PyExc_TypeError, msg);
        return -1;
    }
    if (PyInt_Check(o)) {
        long_value = (longlong) PyInt_AS_LONG(o);
        goto finish;
    } else if (PyLong_Check(o)) {
        long_value = (longlong) PyLong_AsLongLong(o);
        goto finish;
    }

#if SIZEOF_INTP == SIZEOF_LONG
    descr = &LONG_Descr;
#elif SIZEOF_INTP == SIZEOF_INT
    descr = &INT_Descr;
#else
    descr = &LONGLONG_Descr;
#endif
    arr = NULL;

    if (PyArray_Check(o)) {
        if (PyArray_SIZE(o)!=1 || !PyArray_ISINTEGER(o)) {
            PyErr_SetString(PyExc_TypeError, msg);
            return -1;
        }
        Py_INCREF(descr);
        arr = PyArray_CastToType((PyArrayObject *)o, descr, 0);
    }
    else if (PyArray_IsScalar(o, Integer)) {
        Py_INCREF(descr);
        arr = PyArray_FromScalar(o, descr);
    }
    if (arr != NULL) {
        ret = *((intp *)PyArray_DATA(arr));
        Py_DECREF(arr);
        return ret;
    }

#if (PY_VERSION_HEX >= 0x02050000)
    if (PyIndex_Check(o)) {
        PyObject* value = PyNumber_Index(o);
        if (value == NULL) {
            return -1;
        }
        long_value = (longlong) PyInt_AsSsize_t(value);
        goto finish;
    }
#endif
#if !defined(NPY_PY3K)
    if (Py_TYPE(o)->tp_as_number != NULL &&                 \
        Py_TYPE(o)->tp_as_number->nb_long != NULL) {
        obj = Py_TYPE(o)->tp_as_number->nb_long(o);
        if (obj != NULL) {
            long_value = (longlong) PyLong_AsLongLong(obj);
            Py_DECREF(obj);
        }
    }
    else
#endif
    if (Py_TYPE(o)->tp_as_number != NULL &&                 \
             Py_TYPE(o)->tp_as_number->nb_int != NULL) {
        obj = Py_TYPE(o)->tp_as_number->nb_int(o);
        if (obj != NULL) {
            long_value = (longlong) PyLong_AsLongLong(obj);
            Py_DECREF(obj);
        }
    }
    else {
        PyErr_SetString(PyExc_NotImplementedError,"");
    }

 finish:
    if error_converting(long_value) {
            PyErr_SetString(PyExc_TypeError, msg);
            return -1;
        }

#if (SIZEOF_LONGLONG > SIZEOF_INTP)
    if ((long_value < MIN_INTP) || (long_value > MAX_INTP)) {
        PyErr_SetString(PyExc_ValueError,
                        "integer won't fit into a C intp");
        return -1;
    }
#endif
    return (intp) long_value;
}
开发者ID:jpeel,项目名称:numpy,代码行数:98,代码来源:conversion_utils.c

示例3: parse_property

int parse_property( unicap_property_t *property, PyObject *obj )
{   
   PyObject *tmp = NULL;

   tmp = PyDict_GetItemString (obj, "identifier");
   if (tmp){
	   strncpy (property->identifier, PyString_AsString(tmp), sizeof (property->identifier)-1);
   }

   tmp = PyDict_GetItemString (obj, "category");
   if (tmp){
	   strncpy (property->category, PyString_AsString(tmp), sizeof (property->category)-1);
   }

   tmp = PyDict_GetItemString (obj, "unit");
   if (tmp){
	   strncpy (property->unit, PyString_AsString(tmp), sizeof (property->unit)-1);
   }

   tmp = PyDict_GetItemString( obj, "flags" );
   if (tmp){
      Py_ssize_t len,index;
      if (!PyList_Check (tmp)){
	 PyErr_SetString (PyExc_TypeError, "Expected a List for 'flags' item");
	 goto err;
      }
      
      len = PyList_Size( tmp );
      property->flags = 0;
      for (index = 0; index < len; index++){
	 PyObject *item = PyList_GetItem( tmp, index );
	 if (!item)
	    goto err;
	 char *str = PyString_AsString (item);
	 if (!str)
	    goto err;
	 if (!strcmp (str, "manual"))
	    property->flags |= UNICAP_FLAGS_MANUAL;
	 else if (!strcmp (str, "one push"))
	    property->flags |= UNICAP_FLAGS_ONE_PUSH;
	 else if (!strcmp (str, "auto"))
	    property->flags |= UNICAP_FLAGS_AUTO;
      }	 
   }
   


   switch( property->type )
   {
      case UNICAP_PROPERTY_TYPE_RANGE:
      case UNICAP_PROPERTY_TYPE_VALUE_LIST:
      {
	      tmp = PyDict_GetItemString( obj, "value" );
	      if( !tmp ){
		      PyErr_SetString (PyExc_ValueError, "Object is missing 'value' key");
		      goto err;
	      }
	      if (PyFloat_Check (tmp))
		      property->value = PyFloat_AsDouble (tmp);
	      else if (PyInt_Check (tmp))
		      property->value = PyInt_AsLong (tmp);
	      else
		      goto err;

	      tmp = PyDict_GetItemString (obj, "range");
	      if (tmp){
		      PyObject *minval = PyTuple_GetItem (tmp, 0);
		      PyObject *maxval = PyTuple_GetItem (tmp, 1);
		      
		      if (minval){
			      if (PyFloat_Check (minval))
				      property->range.min = PyFloat_AsDouble (minval);
			      else if (PyInt_Check (minval))
				      property->range.min = PyInt_AsLong (minval);
			      else
				      goto err;
		      }
		      
		      if (maxval){
			      if (PyFloat_Check (maxval))
				      property->range.max = PyFloat_AsDouble (maxval);
			      else if (PyInt_Check (maxval))
				      property->range.max = PyInt_AsLong (maxval);
			      else
				      goto err;
		      }
	      }
      }
      break;
      
      case UNICAP_PROPERTY_TYPE_MENU:
      {
	 tmp = PyDict_GetItemString( obj, "menu_item" );
	 if( !tmp ){
	    PyErr_SetString( PyExc_ValueError, "Object is missing 'menu_item' key" );
	    goto err;
	 }
	 if( !PyString_Check( tmp ) )
	 {
	    goto err;
//.........这里部分代码省略.........
开发者ID:gabrielduque,项目名称:unicap-1,代码行数:101,代码来源:utils.c

示例4: test_neighborhood_iterator

static PyObject*
test_neighborhood_iterator(PyObject* NPY_UNUSED(self), PyObject* args)
{
    PyObject *x, *fill, *out, *b;
    PyArrayObject *ax, *afill;
    PyArrayIterObject *itx;
    int i, typenum, mode, st;
    npy_intp bounds[NPY_MAXDIMS*2];
    PyArrayNeighborhoodIterObject *niterx;

    if (!PyArg_ParseTuple(args, "OOOi", &x, &b, &fill, &mode)) {
        return NULL;
    }

    if (!PySequence_Check(b)) {
        return NULL;
    }

    typenum = PyArray_ObjectType(x, 0);
    typenum = PyArray_ObjectType(fill, typenum);

    ax = (PyArrayObject*)PyArray_FromObject(x, typenum, 1, 10);
    if (ax == NULL) {
        return NULL;
    }
    if (PySequence_Size(b) != 2 * PyArray_NDIM(ax)) {
        PyErr_SetString(PyExc_ValueError,
                "bounds sequence size not compatible with x input");
        goto clean_ax;
    }

    out = PyList_New(0);
    if (out == NULL) {
        goto clean_ax;
    }

    itx = (PyArrayIterObject*)PyArray_IterNew(x);
    if (itx == NULL) {
        goto clean_out;
    }

    /* Compute boundaries for the neighborhood iterator */
    for (i = 0; i < 2 * PyArray_NDIM(ax); ++i) {
        PyObject* bound;
        bound = PySequence_GetItem(b, i);
        if (bounds == NULL) {
            goto clean_itx;
        }
        if (!PyInt_Check(bound)) {
            PyErr_SetString(PyExc_ValueError,
                    "bound not long");
            Py_DECREF(bound);
            goto clean_itx;
        }
        bounds[i] = PyInt_AsLong(bound);
        Py_DECREF(bound);
    }

    /* Create the neighborhood iterator */
    afill = NULL;
    if (mode == NPY_NEIGHBORHOOD_ITER_CONSTANT_PADDING) {
            afill = (PyArrayObject *)PyArray_FromObject(fill, typenum, 0, 0);
            if (afill == NULL) {
            goto clean_itx;
        }
    }

    niterx = (PyArrayNeighborhoodIterObject*)PyArray_NeighborhoodIterNew(
                    (PyArrayIterObject*)itx, bounds, mode, afill);
    if (niterx == NULL) {
        goto clean_afill;
    }

    switch (typenum) {
        case NPY_OBJECT:
            st = copy_object(itx, niterx, bounds, &out);
            break;
        case NPY_INT:
            st = copy_int(itx, niterx, bounds, &out);
            break;
        case NPY_DOUBLE:
            st = copy_double(itx, niterx, bounds, &out);
            break;
        default:
            PyErr_SetString(PyExc_ValueError,
                    "Type not supported");
            goto clean_niterx;
    }

    if (st) {
        goto clean_niterx;
    }

    Py_DECREF(niterx);
    Py_XDECREF(afill);
    Py_DECREF(itx);

    Py_DECREF(ax);

    return out;
//.........这里部分代码省略.........
开发者ID:adevabhaktuni,项目名称:LADS,代码行数:101,代码来源:multiarray_tests.c

示例5: register_df

  int register_df(int dtid, PyObject *py_obj)
  {
    // Already registered?
    if ( dfid >= 0 )
      return dfid;

    memset(&df, 0, sizeof(df));
    df.cbsize = sizeof(df);
    df.ud = this;

    PYW_GIL_CHECK_LOCKED_SCOPE();
    do
    {
      ref_t py_attr;

      // name
      if ( !PyW_GetStringAttr(py_obj, S_NAME, &df_name) )
        break;
      df.name = df_name.c_str();

      // menu_name (optional)
      if ( PyW_GetStringAttr(py_obj, S_MENU_NAME, &df_menu_name) )
        df.menu_name = df_menu_name.c_str();

      // props
      py_attr = PyW_TryGetAttrString(py_obj, S_PROPS);
      if ( py_attr != NULL && PyInt_Check(py_attr.o) )
        df.props = PyInt_AsLong(py_attr.o);

      // hotkey
      if ( PyW_GetStringAttr(py_obj, S_HOTKEY, &df_hotkey) )
        df.hotkey = df_hotkey.c_str();

      // value_size
      py_attr = PyW_TryGetAttrString(py_obj, S_VALUE_SIZE);
      if ( py_attr != NULL && PyInt_Check(py_attr.o) )
        df.value_size = PyInt_AsLong(py_attr.o);

      // text_width
      py_attr = PyW_TryGetAttrString(py_obj, S_TEXT_WIDTH);
      if ( py_attr != NULL && PyInt_Check(py_attr.o) )
        df.text_width = PyInt_AsLong(py_attr.o);

      // print cb
      py_attr = PyW_TryGetAttrString(py_obj, S_PRINTF);
      if ( py_attr != NULL && PyCallable_Check(py_attr.o) )
        df.print = s_print;

      // scan cb
      py_attr = PyW_TryGetAttrString(py_obj, S_SCAN);
      if ( py_attr != NULL && PyCallable_Check(py_attr.o) )
        df.scan = s_scan;

      // analyze cb
      py_attr = PyW_TryGetAttrString(py_obj, S_ANALYZE);
      if ( py_attr != NULL && PyCallable_Check(py_attr.o) )
        df.analyze = s_analyze;

      // Now try to register
      dfid = register_custom_data_format(dtid, &df);
      if ( dfid < 0 )
        break;

      // Hold reference to the PyObject
      Py_INCREF(py_obj);
      py_self = py_obj;

      // Update the format ID
      py_attr = newref_t(PyInt_FromLong(dfid));
      PyObject_SetAttrString(py_obj, S_ID, py_attr.o);
    } while ( false );
    return dfid;
  }
开发者ID:EiNSTeiN-,项目名称:idapython,代码行数:73,代码来源:py_custdata.hpp

示例6: _attachsql_QueryObject_Initialize

int _attachsql_QueryObject_Initialize(_attachsql_QueryObject *self, PyObject *args, PyObject *kwargs)
{
  bool ret;
  char *query= NULL;
  int query_length;
  int param_count= 0;
  int i;
  int64_t *tmp_int;
  uint64_t *tmp_uint;
  double *tmp_double;
  attachsql_query_parameter_st *asql_params= NULL;
  PyObject *param_list= NULL;
  PyObject *param_dict= NULL;
  PyObject *type= NULL;
  PyObject *value= NULL;
  PyObject *is_unsigned= NULL;
  attachsql_error_t *error= NULL;
  if (!PyArg_ParseTuple(args, "s#|O!", &query, &query_length, &PyList_Type, &param_list))
  {
    return -1;
  }

  if (!param_list)
  {
    ret= attachsql_query(self->pycon->conn, query_length, query, 0, NULL, &error);
    if (error)
    {
      _attachsql_Exception(error);
      return -1;
    }
    return 0;
  }
  /* For parameters the user should use:
   * .query("SELECT * FROM test WHERE a=? and b=?", [{'type': ESCAPE_TYPE_CHAR, 'data': 'hello'}, {'type': ESCAPE_TYPE_INT, 'data': 1}])
   */
  param_count= PyList_Size(param_list);
  asql_params= (attachsql_query_parameter_st*)malloc(sizeof(attachsql_query_parameter_st) * param_count);
  /* This is ugly, need to find a better way */
  tmp_int= (int64_t*)malloc(sizeof(int64_t) * param_count);
  tmp_uint= (uint64_t*)malloc(sizeof(uint64_t) * param_count);
  tmp_double= (double*)malloc(sizeof(double) * param_count);

  for (i= 0; i < param_count; i++)
  {
    param_dict= PyList_GetItem(param_list, i);
    if (!PyDict_Check(param_dict))
    {
      PyErr_SetString(PyExc_TypeError, "Dict not found in list");
      free(asql_params);
      return -1;
    }
    type= PyDict_GetItemString(param_dict, "type");
    value= PyDict_GetItemString(param_dict, "data");
    is_unsigned= PyDict_GetItemString(param_dict, "is_unsigned");
    if (!type || !value || !PyInt_Check(type))
    {
      PyErr_SetString(PyExc_TypeError, "Bad type or value in dict");
      free(asql_params);
      return -1;
    }
    asql_params[i].type= PyInt_AsLong(type);

    switch (asql_params[i].type)
    {
      case ATTACHSQL_ESCAPE_TYPE_NONE:
        asql_params[i].data= NULL;
        break;
      case ATTACHSQL_ESCAPE_TYPE_CHAR:
      case ATTACHSQL_ESCAPE_TYPE_CHAR_LIKE:
        asql_params[i].data= PyString_AsString(value);
        asql_params[i].length= PyString_Size(value);
        break;
      case ATTACHSQL_ESCAPE_TYPE_INT:
        if (is_unsigned && PyInt_AsLong(is_unsigned))
        {
          if (PyInt_Check(value))
          {
            tmp_uint[i]= PyInt_AsUnsignedLongMask(value);
          }
          else
          {
            tmp_uint[i]= PyLong_AsUnsignedLong(value);
          }
          asql_params[i].data= &tmp_uint[i];
          asql_params[i].is_unsigned= true;
        }
        else
        {
          if (PyInt_Check(value))
          {
            tmp_int[i]= PyInt_AsLong(value);
          }
          else
          {
            tmp_int[i]= PyLong_AsLong(value);
          }
          asql_params[i].data= &tmp_int[i];
          asql_params[i].is_unsigned= false;
        }
        break;
//.........这里部分代码省略.........
开发者ID:LinuxJedi,项目名称:pyattachsql,代码行数:101,代码来源:query.c

示例7: MoleculeAttributes_SetBondSingleColor

/*static*/ PyObject *
MoleculeAttributes_SetBondSingleColor(PyObject *self, PyObject *args)
{
    MoleculeAttributesObject *obj = (MoleculeAttributesObject *)self;

    int c[4];
    if(!PyArg_ParseTuple(args, "iiii", &c[0], &c[1], &c[2], &c[3]))
    {
        c[3] = 255;
        if(!PyArg_ParseTuple(args, "iii", &c[0], &c[1], &c[2]))
        {
            double dr, dg, db, da;
            if(PyArg_ParseTuple(args, "dddd", &dr, &dg, &db, &da))
            {
                c[0] = int(dr);
                c[1] = int(dg);
                c[2] = int(db);
                c[3] = int(da);
            }
            else if(PyArg_ParseTuple(args, "ddd", &dr, &dg, &db))
            {
                c[0] = int(dr);
                c[1] = int(dg);
                c[2] = int(db);
                c[3] = 255;
            }
            else
            {
                PyObject *tuple = NULL;
                if(!PyArg_ParseTuple(args, "O", &tuple))
                    return NULL;

                if(!PyTuple_Check(tuple))
                    return NULL;

                // Make sure that the tuple is the right size.
                if(PyTuple_Size(tuple) < 3 || PyTuple_Size(tuple) > 4)
                    return NULL;

                // Make sure that all elements in the tuple are ints.
                for(int i = 0; i < PyTuple_Size(tuple); ++i)
                {
                    PyObject *item = PyTuple_GET_ITEM(tuple, i);
                    if(PyInt_Check(item))
                        c[i] = int(PyInt_AS_LONG(PyTuple_GET_ITEM(tuple, i)));
                    else if(PyFloat_Check(item))
                        c[i] = int(PyFloat_AS_DOUBLE(PyTuple_GET_ITEM(tuple, i)));
                    else
                        return NULL;
                }
            }
        }
        PyErr_Clear();
    }

    // Set the bondSingleColor in the object.
    ColorAttribute ca(c[0], c[1], c[2], c[3]);
    obj->data->SetBondSingleColor(ca);

    Py_INCREF(Py_None);
    return Py_None;
}
开发者ID:burlen,项目名称:visit_vtk_7_src,代码行数:62,代码来源:PyMoleculeAttributes.C

示例8: frame_setlineno

/* Setter for f_lineno - you can set f_lineno from within a trace function in
 * order to jump to a given line of code, subject to some restrictions.	 Most
 * lines are OK to jump to because they don't make any assumptions about the
 * state of the stack (obvious because you could remove the line and the code
 * would still work without any stack errors), but there are some constructs
 * that limit jumping:
 *
 *  o Lines with an 'except' statement on them can't be jumped to, because
 *    they expect an exception to be on the top of the stack.
 *  o Lines that live in a 'finally' block can't be jumped from or to, since
 *    the END_FINALLY expects to clean up the stack after the 'try' block.
 *  o 'try'/'for'/'while' blocks can't be jumped into because the blockstack
 *    needs to be set up before their code runs, and for 'for' loops the
 *    iterator needs to be on the stack.
 */
static int
frame_setlineno(PyFrameObject *f, PyObject* p_new_lineno)
{
	int new_lineno = 0;		/* The new value of f_lineno */
	int new_lasti = 0;		/* The new value of f_lasti */
	int new_iblock = 0;		/* The new value of f_iblock */
	unsigned short *code = NULL;	/* The bytecode for the frame... */
	Py_ssize_t code_len = 0;	/* ...and its length */
	unsigned char *lnotab = NULL;	/* Iterating over co_lnotab */
	Py_ssize_t lnotab_len = 0;	/* (ditto) */
	int offset = 0;			/* (ditto) */
	int line = 0;			/* (ditto) */
	int addr = 0;			/* (ditto) */
	int min_addr = 0;		/* Scanning the SETUPs and POPs */
	int max_addr = 0;		/* (ditto) */
	int delta_iblock = 0;		/* (ditto) */
	int min_delta_iblock = 0;	/* (ditto) */
	int min_iblock = 0;		/* (ditto) */
	int f_lasti_setup_addr = 0;	/* Policing no-jump-into-finally */
	int new_lasti_setup_addr = 0;	/* (ditto) */
	int blockstack[CO_MAXBLOCKS];	/* Walking the 'finally' blocks */
	int in_finally[CO_MAXBLOCKS];	/* (ditto) */
	int blockstack_top = 0;		/* (ditto) */
	int temp_for_addr_stack[CO_MAXBLOCKS];	/* Temporary target address of
                                               for blocks (no setup) */
	int temp_block_type_stack[CO_MAXBLOCKS];	/* Temporary block kind
                                                   (0 = setup, 1 = for) */
	int temp_for_addr_top = 0;		    /* (ditto) */
	int temp_last_for_addr = -1;        /* (ditto) */
	int temp_block_type_top = 0;	    /* (ditto) */
	int for_addr_stack[CO_MAXBLOCKS];	/* Target address of for blocks
                                           (no setup) */
	int block_type_stack[CO_MAXBLOCKS];	/* Block kind (0 = setup, 1 = for) */
	int for_addr_top;		        /* (ditto) */
	int last_for_addr;	            /* (ditto) */
	int block_type_top;	            /* (ditto) */
	unsigned short setup_op = 0;	/* (ditto) */
	unsigned short op;
    int oparg, target_addr;
	char *tmp;

	/* f_lineno must be an integer. */
	if (!PyInt_Check(p_new_lineno)) {
		PyErr_SetString(PyExc_ValueError,
				"lineno must be an integer");
		return -1;
	}

	/* You can only do this from within a trace function, not via
	 * _getframe or similar hackery. */
	if (!f->f_trace)
	{
		PyErr_Format(PyExc_ValueError,
			     "f_lineno can only be set by a trace function");
		return -1;
	}

	/* Fail if the line comes before the start of the code block. */
	new_lineno = (int) PyInt_AsLong(p_new_lineno);
	if (new_lineno < f->f_code->co_firstlineno) {
		PyErr_Format(PyExc_ValueError,
			     "line %d comes before the current code block",
			     new_lineno);
		return -1;
	}

	/* Find the bytecode offset for the start of the given line, or the
	 * first code-owning line after it. */
	PyString_AsStringAndSize(f->f_code->co_lnotab,
	                         &tmp, &lnotab_len);
	lnotab = (unsigned char *) tmp;
	addr = 0;
	line = f->f_code->co_firstlineno;
	new_lasti = -1;
	for (offset = 0; offset < lnotab_len; offset += 2) {
		addr += lnotab[offset];
		line += lnotab[offset+1];
		if (line >= new_lineno) {
			new_lasti = addr;
			new_lineno = line;
			break;
		}
	}

	/* If we didn't reach the requested line, return an error. */
//.........这里部分代码省略.........
开发者ID:lrq3000,项目名称:wpython2.wpython11,代码行数:101,代码来源:frameobject.c

示例9: AerospikeClient_Info_each

/**
 *******************************************************************************************************
 * Callback for as_info_foreach().
 *
 * @param err                   The as_error to be populated by the function
 *                              with the encountered error if any.
 * @param node                  The current as_node object for which the
 *                              callback is fired by c client.
 * @param req                   The info request string.
 * @param res                   The info response string for current node.
 * @pram udata                  The callback udata containing the host_lookup
 *                              array and the return zval to be populated with
 *                              an entry for current node's info response with
 *                              the node's ID as the key.
 *
 * Returns true if callback is successful, Otherwise false.
 *******************************************************************************************************
 */
static bool AerospikeClient_Info_each(as_error * err, const as_node * node, const char * req, char * res, void * udata)
{
	PyObject * py_err = NULL;
	PyObject * py_ustr = NULL;
	PyObject * py_out = NULL;
	foreach_callback_info_udata* udata_ptr = (foreach_callback_info_udata *) udata;
	as_address* addr = NULL;

	// Need to make sure we have the GIL since we're back in python land now
	PyGILState_STATE gil_state = PyGILState_Ensure();

	if (err && err->code != AEROSPIKE_OK) {
		as_error_update(err, err->code, NULL);
		goto CLEANUP;
	}
	else if (res) {
		char * out = strchr(res,'\t');
		if (out) {
			out++;
			py_out = PyString_FromString(out);
		}
		else {
			py_out = PyString_FromString(res);
		}
	}

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

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

	PyObject * py_res = PyTuple_New(2);
	PyTuple_SetItem(py_res, 0, py_err);
	PyTuple_SetItem(py_res, 1, py_out);

	if (udata_ptr->host_lookup_p) {
		PyObject * py_hosts = (PyObject *)udata_ptr->host_lookup_p;
			if (py_hosts && PyList_Check(py_hosts)) {
				addr = as_node_get_address((as_node *)node);
				int size = (int) PyList_Size(py_hosts);
				for (int i = 0; i < size; i++) {
					char * host_addr = NULL;
					int port = -1;
					PyObject * py_host = PyList_GetItem(py_hosts, i);
					if (PyTuple_Check(py_host) && PyTuple_Size(py_host) == 2) {
						PyObject * py_addr = PyTuple_GetItem(py_host,0);
						PyObject * py_port = PyTuple_GetItem(py_host,1);
						if (PyUnicode_Check(py_addr)) {
							py_ustr = PyUnicode_AsUTF8String(py_addr);
							host_addr = PyBytes_AsString(py_ustr);
						} else if (PyString_Check(py_addr)) {
							host_addr = PyString_AsString(py_addr);
						} else {
							as_error_update(&udata_ptr->error, AEROSPIKE_ERR_PARAM, "Host address is of type incorrect");
							if (py_res) {
								Py_DECREF(py_res);
							}
							PyGILState_Release(gil_state);
							return false;
						}
						if (PyInt_Check(py_port)) {
							port = (uint16_t) PyInt_AsLong(py_port);
						}
						else if (PyLong_Check(py_port)) {
							port = (uint16_t) PyLong_AsLong(py_port);
						} else {
							break;
						}
						char ip_port[IP_PORT_MAX_LEN];
						// If the address is longer than the max length of an ipv6 address, raise an error and exit
						if (strnlen(host_addr, INET6_ADDRSTRLEN) >= INET6_ADDRSTRLEN) {
							as_error_update(&udata_ptr->error, AEROSPIKE_ERR_PARAM, "Host address is too long");
							if (py_res) {
								Py_DECREF(py_res);
							}
							goto CLEANUP;
						}
//.........这里部分代码省略.........
开发者ID:aerospike,项目名称:aerospike-client-python,代码行数:101,代码来源:info.c

示例10: pyobj_send

void pyobj_send(t_outlet*const outlet,PyObject*const value)
{
	if(!value);
	else if(value==Py_True)
		outlet_bang(outlet);
	else if(value==Py_False)
		outlet_symbol(outlet,&s_);
	else if(PyInt_Check(value))
		outlet_float(outlet,PyInt_AsLong(value));
	else if(PyFloat_Check(value))
		outlet_float(outlet,PyFloat_AsDouble(value));
	else if(PyString_Check(value))
		outlet_symbol(outlet,gensym(PyString_AsString(value)));
	else if(PyDict_Check(value))
	{
	}
	else if(PyList_Check(value))
	{
		register int k,K;
		Py_ssize_t size=PyList_Size(value);
		t_atom*atom=(t_atom*)calloc(sizeof(t_atom),size);
		for(k=0,K=size;k<K;++k)
		{
			PyObject*obj=PyList_GetItem(value,k);
			if(!obj)
				SETSYMBOL(atom+k,&s_);
			else if(obj==Py_True)
				SETFLOAT(atom+k,1);
			else if(obj==Py_False)
				SETSYMBOL(atom+k,&s_);
			else if(PyInt_Check(obj))
				SETFLOAT(atom+k,PyInt_AsLong(obj));
			else if(PyFloat_Check(obj))
				SETFLOAT(atom+k,PyFloat_AsDouble(obj));
			else
				SETSYMBOL(atom+k,&s_);
		}
		outlet_list(outlet,gensym("list"),size,atom);
	}
	else if(PyTuple_Check(value))
	{
		register int k,K;
		Py_ssize_t size=PyTuple_Size(value);
		t_atom*atom=(t_atom*)calloc(sizeof(t_atom),size);
		for(k=0,K=size;k<K;++k)
		{
			PyObject*obj=PyTuple_GetItem(value,k);
			if(!obj)
				SETSYMBOL(atom+k,&s_);
			else if(obj==Py_True)
				SETFLOAT(atom+k,1);
			else if(obj==Py_False)
				SETSYMBOL(atom+k,&s_);
			else if(PyInt_Check(obj))
				SETFLOAT(atom+k,PyInt_AsLong(obj));
			else if(PyFloat_Check(obj))
				SETFLOAT(atom+k,PyFloat_AsDouble(obj));
			else
				SETSYMBOL(atom+k,&s_);
		}
		outlet_list(outlet,gensym("list"),size,atom);
	}
}
开发者ID:kotan-kn,项目名称:pdvms,代码行数:63,代码来源:send.c

示例11: image_init

static int image_init(PyImage *self,
                      PyObject *args,
                      PyObject *kwargs)
{
    PyObject *initial;
    int location = OSL_IN_VRAM;
    int pf = OSL_PF_8888;

    if (!PyArg_ParseTuple(args, "O|ii:__init__", &initial, &location, &pf))
       return -1;

    self->location = location;

    if (PyString_Check(initial))
    {
       // Load from file

       char *filename = PyString_AsString(initial);

       self->pImg = oslLoadImageFile(filename, location, pf);

       if (!self->pImg)
       {
          PyErr_SetString(osl_Error, "Could not load image.");
          return -1;
       }
    }
    else if (PyTuple_Check(initial))
    {
       int w, h;

       if (PyTuple_Size(initial) != 2)
       {
          PyErr_SetString(PyExc_TypeError, "Image dimension must be a 2-tuple");
          return -1;
       }

       if (!PyInt_Check(PyTuple_GetItem(initial, 0)))
       {
          PyErr_SetString(PyExc_TypeError, "Image width must be an integer");
          return -1;
       }

       if (!PyInt_Check(PyTuple_GetItem(initial, 1)))
       {
          PyErr_SetString(PyExc_TypeError, "Image height must be an integer");
          return -1;
       }

       w = PyInt_AsLong(PyTuple_GetItem(initial, 0));
       h = PyInt_AsLong(PyTuple_GetItem(initial, 1));

       self->pImg = oslCreateImage(w, h, location, pf);

       if (!self->pImg)
       {
          PyErr_SetString(osl_Error, "Could not create image");
          return -1;
       }
    }
    else
    {
       PyErr_SetString(PyExc_TypeError, "First argument must be a filename or a 2-tuple");
       return -1;
    }

    if (location == OSL_IN_VRAM)
    {
       FREEIMG *pFree = (FREEIMG*)malloc(sizeof(FREEIMG));

       pFree->bDelete = 0;
       pFree->pImg = self->pImg;
       pFree->next = (void*)pCurrent;
       pCurrent = pFree;
    }

    return 0;
}
开发者ID:Oize,项目名称:pspstacklesspython,代码行数:78,代码来源:image.c

示例12: qpyqml_convertTo_QJSValue

// Convert a Python object to a QJSValue.
int qpyqml_convertTo_QJSValue(PyObject *py, PyObject *transferObj,
        QJSValue **cpp, int *isErr)
{
    if (PyObject_TypeCheck(py, sipTypeAsPyTypeObject(sipType_QJSValue_SpecialValue)))
    {
        *cpp = new QJSValue((QJSValue::SpecialValue)SIPLong_AsLong(py));

        return sipGetState(transferObj);
    }

    if (PyBool_Check(py))
    {
        *cpp = new QJSValue(py == Py_True);

        return sipGetState(transferObj);
    }

#if PY_MAJOR_VERSION >= 3
    if (PyLong_Check(py))
    {
        *cpp = new QJSValue((int)PyLong_AS_LONG(py));

        return sipGetState(transferObj);
    }
#else
    if (PyInt_Check(py))
    {
        *cpp = new QJSValue((int)PyInt_AS_LONG(py));

        return sipGetState(transferObj);
    }
#endif

    if (PyFloat_Check(py))
    {
        *cpp = new QJSValue((double)PyFloat_AS_DOUBLE(py));

        return sipGetState(transferObj);
    }

    if (sipCanConvertToType(py, sipType_QString, 0))
    {
        int state;
        QString *qs = reinterpret_cast<QString *>(sipConvertToType(py,
                sipType_QString, 0, 0, &state, isErr));

        if (*isErr)
        {
            sipReleaseType(qs, sipType_QString, state);
            return 0;
        }

        *cpp = new QJSValue(*qs);

        sipReleaseType(qs, sipType_QString, state);

        return sipGetState(transferObj);
    }

    *cpp = reinterpret_cast<QJSValue *>(sipConvertToType(py, sipType_QJSValue,
            transferObj, SIP_NO_CONVERTORS, 0, isErr));

    return 0;
}
开发者ID:HunterChen,项目名称:pyqt5,代码行数:65,代码来源:qpyqml_qjsvalue.cpp

示例13: archpy_disassemble

static PyObject *
archpy_disassemble (PyObject *self, PyObject *args, PyObject *kw)
{
  static char *keywords[] = { "start_pc", "end_pc", "count", NULL };
  CORE_ADDR start, end = 0;
  CORE_ADDR pc;
  gdb_py_ulongest start_temp;
  long count = 0, i;
  PyObject *result_list, *end_obj = NULL, *count_obj = NULL;
  struct gdbarch *gdbarch = NULL;

  ARCHPY_REQUIRE_VALID (self, gdbarch);

  if (!PyArg_ParseTupleAndKeywords (args, kw, GDB_PY_LLU_ARG "|OO", keywords,
                                    &start_temp, &end_obj, &count_obj))
    return NULL;

  start = start_temp;
  if (end_obj)
    {
      /* Make a long logic check first.  In Python 3.x, internally,
	 all integers are represented as longs.  In Python 2.x, there
	 is still a differentiation internally between a PyInt and a
	 PyLong.  Explicitly do this long check conversion first. In
	 GDB, for Python 3.x, we #ifdef PyInt = PyLong.  This check has
	 to be done first to ensure we do not lose information in the
	 conversion process.  */
      if (PyLong_Check (end_obj))
        end = PyLong_AsUnsignedLongLong (end_obj);
      else if (PyInt_Check (end_obj))
        /* If the end_pc value is specified without a trailing 'L', end_obj will
           be an integer and not a long integer.  */
        end = PyInt_AsLong (end_obj);
      else
        {
          Py_DECREF (end_obj);
          Py_XDECREF (count_obj);
          PyErr_SetString (PyExc_TypeError,
                           _("Argument 'end_pc' should be a (long) integer."));

          return NULL;
        }

      if (end < start)
        {
          Py_DECREF (end_obj);
          Py_XDECREF (count_obj);
          PyErr_SetString (PyExc_ValueError,
                           _("Argument 'end_pc' should be greater than or "
                             "equal to the argument 'start_pc'."));

          return NULL;
        }
    }
  if (count_obj)
    {
      count = PyInt_AsLong (count_obj);
      if (PyErr_Occurred () || count < 0)
        {
          Py_DECREF (count_obj);
          Py_XDECREF (end_obj);
          PyErr_SetString (PyExc_TypeError,
                           _("Argument 'count' should be an non-negative "
                             "integer."));

          return NULL;
        }
    }

  result_list = PyList_New (0);
  if (result_list == NULL)
    return NULL;

  for (pc = start, i = 0;
       /* All args are specified.  */
       (end_obj && count_obj && pc <= end && i < count)
       /* end_pc is specified, but no count.  */
       || (end_obj && count_obj == NULL && pc <= end)
       /* end_pc is not specified, but a count is.  */
       || (end_obj == NULL && count_obj && i < count)
       /* Both end_pc and count are not specified.  */
       || (end_obj == NULL && count_obj == NULL && pc == start);)
    {
      int insn_len = 0;
      char *as = NULL;
      struct ui_file *memfile = mem_fileopen ();
      PyObject *insn_dict = PyDict_New ();

      if (insn_dict == NULL)
        {
          Py_DECREF (result_list);
          ui_file_delete (memfile);

          return NULL;
        }
      if (PyList_Append (result_list, insn_dict))
        {
          Py_DECREF (result_list);
          Py_DECREF (insn_dict);
          ui_file_delete (memfile);
//.........这里部分代码省略.........
开发者ID:ChrisG0x20,项目名称:gdb,代码行数:101,代码来源:py-arch.c

示例14: SPI_xfer2

static PyObject *
SPI_xfer2(SPI *self, PyObject *args)
{
	static char *msg = "Argument must be a list of at least one, "
				"but not more than 1024 integers";
	int status;	
	uint8_t ii, len;
	PyObject *list;
	struct spi_ioc_transfer	xfer;
	uint8_t *txbuf, *rxbuf;

	if (!PyArg_ParseTuple(args, "O:xfer2", &list))
		return NULL;

	if (!PyList_Check(list)) {
		PyErr_SetString(PyExc_TypeError, wrmsg);
		return NULL;
	}

	if ((len = PyList_GET_SIZE(list)) > MAXMSGLEN) {
		PyErr_SetString(PyExc_OverflowError, wrmsg);
		return NULL;
	}

	txbuf = malloc(sizeof(__u8) * len);
	rxbuf = malloc(sizeof(__u8) * len);

	for (ii = 0; ii < len; ii++) {
		PyObject *val = PyList_GET_ITEM(list, ii);
		if (!PyInt_Check(val)) {
			PyErr_SetString(PyExc_TypeError, msg);
			return NULL;
		}
		txbuf[ii] = (__u8)PyInt_AS_LONG(val);
	}

	xfer.tx_buf = (unsigned long)txbuf;
	xfer.rx_buf = (unsigned long)rxbuf;
	xfer.len = len;
	xfer.delay_usecs = 0;
	xfer.speed_hz = 0;      
	xfer.bits_per_word = 0;
	
	status = ioctl(self->fd, SPI_IOC_MESSAGE(1), &xfer);
	if (status < 0) {
		PyErr_SetFromErrno(PyExc_IOError);
		return NULL;
	}

	for (ii = 0; ii < len; ii++) {
		PyObject *val = Py_BuildValue("l", (long)rxbuf[ii]);
		PyList_SET_ITEM(list, ii, val);
	}
	// WA:
	// in CS_HIGH mode CS isnt pulled to low after transfer
	// reading 0 bytes doesn't really matter but brings CS down
	status = read(self->fd, &rxbuf[0], 0);

	free(txbuf);
	free(rxbuf);

	Py_INCREF(list);
	return list;
}
开发者ID:Aridono,项目名称:adafruit-beaglebone-io-python,代码行数:64,代码来源:spimodule.c

示例15: GetInputDataTree


//.........这里部分代码省略.........
                     "Python Expression 'execute' method must return a sequence of "
                     "data sets & a sequence of domain_ids");

    Py_DECREF(py_dsets);
    Py_DECREF(py_domids);
    Py_DECREF(py_exe);


    // result should be a list with datasets and domain ids

    PyObject *py_result_dsets  = PySequence_GetItem(py_exe_res,0);
    PyObject *py_result_domids = PySequence_GetItem(py_exe_res,1);

    

    if(py_result_dsets == NULL || PySequence_Check(py_result_dsets) == 0)
        PYEXPR_ERROR("avtPythonExpression::Execute Error - "
                     "Python Expression execute method must return a sequence of "
                     "data sets & a sequence of domain_ids");

    if(py_result_domids == NULL || PySequence_Check(py_result_domids) == 0)
        PYEXPR_ERROR("avtPythonExpression::Execute Error - "
                     "Python Expression execute method must return a sequence of "
                     "data sets & a sequence of domain_ids");

    PyObject *py_r_dsets  = PySequence_Fast(py_result_dsets,"Expected Sequence");
    PyObject *py_r_domids = PySequence_Fast(py_result_domids,"Expected Sequence");

    if(py_r_dsets == NULL || py_r_domids == NULL)
        PYEXPR_ERROR("avtPythonExpression::Execute Error - "
                     "Unable to obtain result sequences.");


    // int n_r_dsets  = PySequence_Size(py_r_dsets);
    // int n_r_domids = PySequence_Size(py_r_domids);

    // check that the lists are the correct size?

    std::vector<vtkDataSet*> res_dsets;
    std::vector<int>         res_domids;
    
    // process all local sets
    for(int i = 0; i < nsets ; i++)
    {
        // get current set
        vtkDataSet *res_dset = NULL; // fetch each set from vtk output
        int         res_domid = -1;

        PyObject *py_dset  = PySequence_Fast_GET_ITEM(py_r_dsets,i);  // borrowed
        PyObject *py_domid = PySequence_Fast_GET_ITEM(py_r_domids,i); // borrowed
        
        if(py_dset == NULL)
            PYEXPR_ERROR("avtPythonExpression::Execute Error - "
                         "Unable fetch result data set.");

        if(py_dset != Py_None) // allow 'None' as return
        {
            res_dset = (vtkDataSet*) pyEnv->UnwrapVTKObject(py_dset,"vtkDataSet");
            if(res_dset == NULL)
                PYEXPR_ERROR("avtPythonExpression::Execute Error - "
                             "Error unwraping vtkDataSet result.");
             if(py_domid == NULL || PyInt_Check(py_domid) == 0)
                 PYEXPR_ERROR("avtPythonExpression::Execute Error - "
                              "Unable fetch result domain id.");
             res_domid = (int) PyInt_AsLong(py_domid);
        }
        
        res_dsets.push_back(res_dset);
        res_domids.push_back(res_domid);
    }
    
    // if we have no errors, register the datasets & create the output 
    // data tree
    for(int i = 0; i < nsets ; i++)
    {
        if(res_dsets[i]) // add result as new leaf
        {
            res_dsets[i]->Register(NULL);
            leaves[i] = new avtDataTree(res_dsets[i],res_domids[i]);
        }
        else // if the dataset only contained ghost zones we could end up here
            leaves[i] = NULL;
        
    }

    Py_DECREF(py_result_dsets);
    Py_DECREF(py_result_domids);
    Py_DECREF(py_r_dsets);
    Py_DECREF(py_r_domids);
    Py_DECREF(py_exe_res);

    // create output data tree
    avtDataTree_p result_tree = new avtDataTree(nsets,leaves);
    // set output data tree
    SetOutputDataTree(result_tree);

    // cleanup leaves array
    delete [] leaves;

}
开发者ID:HarinarayanKrishnan,项目名称:VisIt27RC_Trunk,代码行数:101,代码来源:avtPythonExpression.C


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