• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C++ PyLong_AsLong函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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

示例1: PyInt_CheckExact

static PyObject *qdbusargument_add(QDBusArgument *arg, PyObject *obj, int mtype)
{
    int iserr = 0;

    if (PyLong_CheckExact(obj)
#if PY_MAJOR_VERSION < 3
            || PyInt_CheckExact(obj)
#endif
            )
    {
        if (mtype == QMetaType::UChar || mtype == QMetaType::UShort || mtype == QMetaType::UInt || mtype == QMetaType::ULongLong)
        {
            // Handle the unsigned values.
#if defined(HAVE_LONG_LONG)
            unsigned PY_LONG_LONG v = PyLong_AsUnsignedLongLongMask(obj);
#else
            unsigned long v = PyLong_AsUnsignedLongMask(obj);
#endif

            switch (mtype)
            {
            case QMetaType::UChar:
                *arg << (uchar)v;
                break;

            case QMetaType::UShort:
                *arg << (ushort)v;
                break;

            case QMetaType::UInt:
                *arg << (uint)v;
                break;

            case QMetaType::ULongLong:
                *arg << (qulonglong)v;
                break;
            }
        }
        else if (mtype == QMetaType::Short || mtype == QMetaType::Int || mtype == QMetaType::LongLong)
        {
            // Handle the signed values.
#if defined(HAVE_LONG_LONG)
            PY_LONG_LONG v = PyLong_AsLongLong(obj);
#else
            long v = PyLong_AsLong(obj);
#endif

            switch (mtype)
            {
            case QMetaType::Short:
                *arg << (short)v;
                break;

            case QMetaType::Int:
                *arg << (int)v;
                break;

            case QMetaType::LongLong:
                *arg << (qlonglong)v;
                break;
            }
        }
        else
        {
            PyErr_Format(PyExc_ValueError,
                    "%d is an invalid QMetaType::Type for an interger object",
                    mtype);
            iserr = 1;
        }
    }
    else if (mtype == QMetaType::QStringList)
    {
        // A QStringList has to be handled explicitly to prevent it being seen
        // as a vialiant list.

        int value_state;

        QStringList *qsl = reinterpret_cast<QStringList *>(
                sipForceConvertToType(obj, sipType_QStringList, 0,
                        SIP_NOT_NONE, &value_state, &iserr));

        if (!iserr)
        {
            arg->beginArray(QMetaType::QString);

            for (int i = 0; i < qsl->count(); ++i)
                *arg << qsl->at(i);

            arg->endArray();

            sipReleaseType(qsl, sipType_QStringList, value_state);
        }
    }
    else
    {
        int value_state;

        QVariant *qv = reinterpret_cast<QVariant *>(
                sipForceConvertToType(obj, sipType_QVariant, 0, SIP_NOT_NONE,
                        &value_state, &iserr));
//.........这里部分代码省略.........
开发者ID:annelida,项目名称:stuff,代码行数:101,代码来源:sipQtDBusQDBusArgument.cpp


示例2: set_integer_array_from_python

void set_integer_array_from_python(char* function, int* function_len, int* dim, 
                                   int* nodes, 
                                   double x[], double y[], double z[], double* t,  
                                   int* result, int* stat)
{
#ifndef HAVE_PYTHON
  int i;
  strncpy(function, "No Python support!\n", (size_t) *function_len);
  for (i=0; i < *function_len; i++)
  {
    if (function[i] == '\0')
      function[i] = ' ';
  }
  *stat=1;
  return;
#else
  PyObject *pMain, *pGlobals, *pLocals, *pFunc, *pCode, *pResult, 
    *pArgs, *pPos, *px, *pT;
  
  char *function_c;
  int i;
  
  // the function string passed down from Fortran needs terminating,
  // so make a copy and fiddle with it (remember to free it)
  function_c = (char *)malloc(*function_len+3);
  memcpy( function_c, function, *function_len );
  function_c[*function_len] = 0;

  // Get a reference to the main module and global dictionary
  pMain = PyImport_AddModule("__main__");

  pGlobals = PyModule_GetDict(pMain);
  // Global and local namespace dictionaries for our code.
  pLocals=PyDict_New();
  
  // Execute the user's code.
  pCode=PyRun_String(function_c, Py_file_input, pGlobals, pLocals);

  // Extract the function from the code.
  pFunc=PyDict_GetItemString(pLocals, "val");

  // Clean up memory from null termination.
  free(function_c);
  
  // Check for errors in executing user code.
  if (PyErr_Occurred()){
    PyErr_Print();
    *stat=1;
    return;
  }

  // Python form of time variable.
  pT=PyFloat_FromDouble(*t);

  // Tuple containing the current position vector.
  pPos=PyTuple_New(*dim);

  // Tuple of arguments to function;
  pArgs=PyTuple_New(2);
  PyTuple_SetItem(pArgs, 1, pT);
  PyTuple_SetItem(pArgs, 0, pPos);

  // Check for a Python error in the function call
  if (PyErr_Occurred()){
    PyErr_Print();
    *stat=1;
    return;
  }

  for (i = 0; i < *nodes; i++){
    px=PyFloat_FromDouble(x[i]);
    PyTuple_SetItem(pPos, 0, px);    

    if (*dim>1) {
      px=PyFloat_FromDouble(y[i]);
      PyTuple_SetItem(pPos, 1, px);

      if (*dim>2) {
        px=PyFloat_FromDouble(z[i]);
        PyTuple_SetItem(pPos, 2, px);
      }
    }

    pResult=PyObject_CallObject(pFunc, pArgs); 
    
    // Check for a Python error in the function call
    if (PyErr_Occurred()){
      PyErr_Print();
      *stat=1;
      return;
    }
    
    result[i]=PyLong_AsLong(pResult);

    // Check for a Python error in result.
    if (PyErr_Occurred()){
      PyErr_Print();
      *stat=1;
      return;
    }
//.........这里部分代码省略.........
开发者ID:Nasrollah,项目名称:fluidity,代码行数:101,代码来源:embed_python.c


示例3: BaseRowProxy_subscript

static PyObject *
BaseRowProxy_subscript(BaseRowProxy *self, PyObject *key)
{
    PyObject *processors, *values;
    PyObject *processor, *value, *processed_value;
    PyObject *row, *record, *result, *indexobject;
    PyObject *exc_module, *exception;
    char *cstr_key;
    long index;
    int key_fallback = 0;
    int tuple_check = 0;
    
    if (PyInt_CheckExact(key)) {
        index = PyInt_AS_LONG(key);
    } else if (PyLong_CheckExact(key)) {
        index = PyLong_AsLong(key);
        if ((index == -1) && PyErr_Occurred())
            /* -1 can be either the actual value, or an error flag. */
            return NULL;
    } else if (PySlice_Check(key)) {
        values = PyObject_GetItem(self->row, key);
        if (values == NULL)
            return NULL;

        processors = PyObject_GetItem(self->processors, key);
        if (processors == NULL) {
            Py_DECREF(values);
            return NULL;
        }

        result = BaseRowProxy_processvalues(values, processors, 1);
        Py_DECREF(values);
        Py_DECREF(processors);
        return result;
    } else {
        record = PyDict_GetItem((PyObject *)self->keymap, key);
        if (record == NULL) {
            record = PyObject_CallMethod(self->parent, "_key_fallback",
                                         "O", key);
            if (record == NULL)
                return NULL;
            key_fallback = 1;
        }

        indexobject = PyTuple_GetItem(record, 2);
        if (indexobject == NULL)
            return NULL;

        if (key_fallback) {
            Py_DECREF(record);
        }

        if (indexobject == Py_None) {
            exc_module = PyImport_ImportModule("sqlalchemy.exc");
            if (exc_module == NULL)
                return NULL;

            exception = PyObject_GetAttrString(exc_module,
                                               "InvalidRequestError");
            Py_DECREF(exc_module);
            if (exception == NULL)
                return NULL;

            cstr_key = PyString_AsString(key);
            if (cstr_key == NULL)
                return NULL;

            PyErr_Format(exception,
                    "Ambiguous column name '%.200s' in result set! "
                    "try 'use_labels' option on select statement.", cstr_key);
            return NULL;
        }

        index = PyInt_AsLong(indexobject);
        if ((index == -1) && PyErr_Occurred())
            /* -1 can be either the actual value, or an error flag. */
            return NULL;
    }
    processor = PyList_GetItem(self->processors, index);
    if (processor == NULL)
        return NULL;

    row = self->row;
    if (PyTuple_CheckExact(row)) {
        value = PyTuple_GetItem(row, index);
        tuple_check = 1;
    }
    else {
        value = PySequence_GetItem(row, index);
        tuple_check = 0;
    }
        
    if (value == NULL)
        return NULL;

    if (processor != Py_None) {
        processed_value = PyObject_CallFunctionObjArgs(processor, value, NULL);
        if (!tuple_check) {
            Py_DECREF(value);
        }
//.........这里部分代码省略.........
开发者ID:acbart,项目名称:WebInACan,代码行数:101,代码来源:resultproxy.c


示例4: AerospikeClient_InfoNode_Invoke

/**
 ******************************************************************************************************
 * Returns data for a particular request string to AerospikeClient_InfoNode
 *
 * @param self                  AerospikeClient object
 * @param request_str_p         Request string sent from the python client
 * @param py_host               Optional host sent from the python client
 * @param py_policy             The policy sent from the python client
 *
 * Returns information about a host.
 ********************************************************************************************************/
static PyObject * AerospikeClient_InfoNode_Invoke(
	AerospikeClient * self,
	PyObject * py_request_str, PyObject * py_host, PyObject * py_policy) {

	PyObject * py_response = NULL;
	PyObject * py_ustr = NULL;
	PyObject * py_ustr1 = NULL;
	as_policy_info info_policy;
	as_policy_info* info_policy_p = NULL;
	char* address = (char *) self->as->config.hosts[0].addr;
	long port_no = self->as->config.hosts[0].port;
	char* response_p = NULL;
	as_status status = AEROSPIKE_OK;

	as_error err;
	as_error_init(&err);

	if (!self || !self->as) {
		as_error_update(&err, AEROSPIKE_ERR_PARAM, "Invalid aerospike object");
		goto CLEANUP;
	}

	if (!self->is_conn_16) {
		as_error_update(&err, AEROSPIKE_ERR_CLUSTER, "No connection to aerospike cluster");
		goto CLEANUP;
	}

	if (py_policy) {
		if( PyDict_Check(py_policy) ) {
			pyobject_to_policy_info(&err, py_policy, &info_policy, &info_policy_p,
					&self->as->config.policies.info);
			if (err.code != AEROSPIKE_OK) {
				goto CLEANUP;
			}
		} else {
			as_error_update(&err, AEROSPIKE_ERR_PARAM, "Policy should be a dictionary");
			goto CLEANUP;
		}
	}

	if ( py_host ) {
		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 ( PyStr_Check(py_addr) ) {
				address = PyStr_AsString(py_addr);
			} else if (PyUnicode_Check(py_addr)) {
				py_ustr = PyUnicode_AsUTF8String(py_addr);
				address = PyStr_AsString(py_ustr);
			}
			if ( PyInt_Check(py_port) ) {
				port_no = (uint16_t) PyInt_AsLong(py_port);
			}
			else if ( PyLong_Check(py_port) ) {
				port_no = (uint16_t) PyLong_AsLong(py_port);
			}
		} else if ( !PyTuple_Check(py_host)){
			as_error_update(&err, AEROSPIKE_ERR_PARAM, "Host should be a specified in form of Tuple.");
			goto CLEANUP;
		}
	}

	char * request_str_p = NULL;
	if (PyUnicode_Check(py_request_str)) {
		py_ustr1 = PyUnicode_AsUTF8String(py_request_str);
		request_str_p = PyStr_AsString(py_ustr1);
	} else if (PyStr_Check(py_request_str)) {
		request_str_p = PyStr_AsString(py_request_str);
	} else {
		as_error_update(&err, AEROSPIKE_ERR_PARAM, "Request should be of string type");
		goto CLEANUP;
	}

    Py_BEGIN_ALLOW_THREADS
	status = aerospike_info_host(self->as, &err, info_policy_p,
		(const char *) address, (uint16_t) port_no, request_str_p,
		&response_p);
    Py_END_ALLOW_THREADS
	if( err.code == AEROSPIKE_OK ) {
		if (response_p && status == AEROSPIKE_OK){
			py_response = PyStr_FromString(response_p);
			free(response_p);
		} else if ( response_p == NULL){
			as_error_update(&err, AEROSPIKE_ERR_CLIENT, "Invalid info operation");
			goto CLEANUP;
		} else if ( status != AEROSPIKE_OK ){
			as_error_update(&err, status, "Info operation failed");
			goto CLEANUP;
//.........这里部分代码省略.........
开发者ID:Fabma,项目名称:aerospike-client-python,代码行数:101,代码来源:info_node.c


示例5: PyArray_PyIntAsIntp_ErrMsg

static npy_intp
PyArray_PyIntAsIntp_ErrMsg(PyObject *o, const char * msg)
{
#if (NPY_SIZEOF_LONG < NPY_SIZEOF_INTP)
    long long long_value = -1;
#else
    long long_value = -1;
#endif
    PyObject *obj, *err;

    if (!o) {
        PyErr_SetString(PyExc_TypeError, msg);
        return -1;
    }

    /* Be a bit stricter and not allow bools, np.bool_ is handled later */
    if (PyBool_Check(o)) {
        if (DEPRECATE("using a boolean instead of an integer"
                      " will result in an error in the future") < 0) {
            return -1;
        }
    }

    /*
     * Since it is the usual case, first check if o is an integer. This is
     * an exact check, since otherwise __index__ is used.
     */
#if !defined(NPY_PY3K)
    if (PyInt_CheckExact(o)) {
  #if (NPY_SIZEOF_LONG <= NPY_SIZEOF_INTP)
        /* No overflow is possible, so we can just return */
        return PyInt_AS_LONG(o);
  #else
        long_value = PyInt_AS_LONG(o);
        goto overflow_check;
  #endif
    }
    else
#endif
    if (PyLong_CheckExact(o)) {
#if (NPY_SIZEOF_LONG < NPY_SIZEOF_INTP)
        long_value = PyLong_AsLongLong(o);
#else
        long_value = PyLong_AsLong(o);
#endif
        return (npy_intp)long_value;
    }

    /* Disallow numpy.bool_. Boolean arrays do not currently support index. */
    if (PyArray_IsScalar(o, Bool)) {
        if (DEPRECATE("using a boolean instead of an integer"
                      " will result in an error in the future") < 0) {
            return -1;
        }
    }

    /*
     * The most general case. PyNumber_Index(o) covers everything
     * including arrays. In principle it may be possible to replace
     * the whole function by PyIndex_AsSSize_t after deprecation.
     */
    obj = PyNumber_Index(o);
    if (obj) {
#if (NPY_SIZEOF_LONG < NPY_SIZEOF_INTP)
        long_value = PyLong_AsLongLong(obj);
#else
        long_value = PyLong_AsLong(obj);
#endif
        Py_DECREF(obj);
        goto finish;
    }
    else {
        /*
         * Set the TypeError like PyNumber_Index(o) would after trying
         * the general case.
         */
        PyErr_Clear();
    }

    /*
     * For backward compatibility check the number C-Api number protcol
     * This should be removed up the finish label after deprecation.
     */
    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) {
            return -1;
        }
 #if (NPY_SIZEOF_LONG < NPY_SIZEOF_INTP)
        long_value = PyLong_AsLongLong(obj);
 #else
        long_value = PyLong_AsLong(obj);
 #endif
        Py_DECREF(obj);
    }
#if !defined(NPY_PY3K)
    else 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);
//.........这里部分代码省略.........
开发者ID:alphaitis,项目名称:numpy,代码行数:101,代码来源:conversion_utils.c


示例6: obf_encode_circuit


//.........这里部分代码省略.........
	vec_to_mpz_array(alphas,alpha_send);
	vec_to_mpz_array(betas,beta_send);


	fprintf(stderr,"Process %d has g[0] = %lu\n",rank,mpz_get_ui(s->mlm.gs[0]));
	fprintf(stderr,"Process %d has pzt = %lu\n",rank,mpz_get_ui(s->mlm.pzt));
	fprintf(stderr,"Process %d has alpha = %lu\n",rank,mpz_get_ui(alphas[2]));

    // The index set is laid out as follows:
    //   - The first 2 * n entries contain X_i,0 and X_i,1
    //   - The next n entries contain Z_i
    //   - The next n entries contain W_i
    //   - The final entry contains Y
    idx_set_size = 4 * n + 1;

    indices = (int *) malloc(sizeof(int) * idx_set_size);
    pows = (int *) malloc(sizeof(int) * idx_set_size);


	//MR
	fprintf(stderr, "m: %d , n: %d \n ", m,n);

	


    for (int i = start_n_loop; i <stop_n_loop ; ++i) {
	fprintf(stderr,"In loop: %d\n",i);        
	mpz_t out, elems[2];
        int deg;
	
	
        mpz_inits(out, elems[0], elems[1], NULL);

        deg = PyLong_AsLong(PyList_GET_ITEM(py_xdegs, i));


	//MR
	//fprintf(stderr, "%d, " ,deg);

        set_indices_pows(indices, pows, 1, 2 * i, 1);
        mpz_set_ui(elems[0], 0);
        mpz_set(elems[1], alphas[i]);
        clt_mlm_encode(&s->mlm, out, 2, elems, 1, indices, pows);
        (void) snprintf(fname, fnamelen, "x_%d_0", i);
        (void) write_element(s->dir, out, fname);
	fprintf(stderr,"Past 1st encode In loop: %d\n",i); 

        set_indices_pows(indices, pows, 1, 2 * i, 1);
        mpz_set_ui(elems[0], 1);
        mpz_set_ui(elems[1], 1);
        clt_mlm_encode(&s->mlm, out, 2, elems, 1, indices, pows);
        (void) snprintf(fname, fnamelen, "u_%d_0", i);
        (void) write_element(s->dir, out, fname);

        set_indices_pows(indices, pows, 1, 2 * i + 1, 1);
        mpz_set_ui(elems[0], 1);
        mpz_set(elems[1], alphas[i]);
        clt_mlm_encode(&s->mlm, out, 2, elems, 1, indices, pows);
	fprintf(stderr,"Past Third encode In loop: %d\n",i);
        (void) snprintf(fname, fnamelen, "x_%d_1", i);
        (void) write_element(s->dir, out, fname);

        set_indices_pows(indices, pows, 1, 2 * i + 1, 1);
        mpz_set_ui(elems[0], 1);
        mpz_set_ui(elems[1], 1);
        clt_mlm_encode(&s->mlm, out, 2, elems, 1, indices, pows);
开发者ID:CyberPoint,项目名称:Obfuscation,代码行数:67,代码来源:_zobfuscator.cpp


示例7: convert_binary

static int convert_binary(struct srd_decoder_inst *di, PyObject *obj,
		struct srd_proto_data *pdata)
{
	struct srd_proto_data_binary *pdb;
	PyObject *py_tmp;
	Py_ssize_t size;
	int bin_class;
	char *class_name, *buf;

	/* Should be a tuple of (binary class, bytes). */
	if (!PyTuple_Check(obj)) {
		srd_err("Protocol decoder %s submitted SRD_OUTPUT_BINARY with "
				"%s instead of tuple.", di->decoder->name,
				obj->ob_type->tp_name);
		return SRD_ERR_PYTHON;
	}

	/* Should have 2 elements. */
	if (PyTuple_Size(obj) != 2) {
		srd_err("Protocol decoder %s submitted SRD_OUTPUT_BINARY tuple "
				"with %d elements instead of 2", di->decoder->name,
				PyList_Size(obj));
		return SRD_ERR_PYTHON;
	}

	/* The first element should be an integer. */
	py_tmp = PyTuple_GetItem(obj, 0);
	if (!PyLong_Check(py_tmp)) {
		srd_err("Protocol decoder %s submitted SRD_OUTPUT_BINARY tuple, "
			"but first element was not an integer.", di->decoder->name);
		return SRD_ERR_PYTHON;
	}
	bin_class = PyLong_AsLong(py_tmp);
	if (!(class_name = g_slist_nth_data(di->decoder->binary, bin_class))) {
		srd_err("Protocol decoder %s submitted SRD_OUTPUT_BINARY with "
			"unregistered binary class %d.", di->decoder->name, bin_class);
		return SRD_ERR_PYTHON;
	}

	/* Second element should be bytes. */
	py_tmp = PyTuple_GetItem(obj, 1);
	if (!PyBytes_Check(py_tmp)) {
		srd_err("Protocol decoder %s submitted SRD_OUTPUT_BINARY tuple, "
			"but second element was not bytes.", di->decoder->name);
		return SRD_ERR_PYTHON;
	}

	/* Consider an empty set of bytes a bug. */
	if (PyBytes_Size(py_tmp) == 0) {
		srd_err("Protocol decoder %s submitted SRD_OUTPUT_BINARY "
				"with empty data set.", di->decoder->name);
		return SRD_ERR_PYTHON;
	}

	if (!(pdb = g_try_malloc(sizeof(struct srd_proto_data_binary))))
		return SRD_ERR_MALLOC;
	if (PyBytes_AsStringAndSize(py_tmp, &buf, &size) == -1)
		return SRD_ERR_PYTHON;
	pdb->bin_class = bin_class;
	pdb->size = size;
	if (!(pdb->data = g_try_malloc(pdb->size)))
		return SRD_ERR_MALLOC;
	memcpy((void *)pdb->data, (const void *)buf, pdb->size);
	pdata->data = pdb;

	return SRD_OK;
}
开发者ID:jfrkuska,项目名称:sigrokdecode,代码行数:67,代码来源:type_decoder.c


示例8: format_long_internal

static int
format_long_internal(PyObject *value, const InternalFormatSpec *format,
                     _PyUnicodeWriter *writer)
{
    int result = -1;
    Py_UCS4 maxchar = 127;
    PyObject *tmp = NULL;
    Py_ssize_t inumeric_chars;
    Py_UCS4 sign_char = '\0';
    Py_ssize_t n_digits;       /* count of digits need from the computed
                                  string */
    Py_ssize_t n_remainder = 0; /* Used only for 'c' formatting, which
                                   produces non-digits */
    Py_ssize_t n_prefix = 0;   /* Count of prefix chars, (e.g., '0x') */
    Py_ssize_t n_total;
    Py_ssize_t prefix = 0;
    NumberFieldWidths spec;
    long x;

    /* Locale settings, either from the actual locale or
       from a hard-code pseudo-locale */
    LocaleInfo locale = STATIC_LOCALE_INFO_INIT;

    /* no precision allowed on integers */
    if (format->precision != -1) {
        PyErr_SetString(PyExc_ValueError,
                        "Precision not allowed in integer format specifier");
        goto done;
    }

    /* special case for character formatting */
    if (format->type == 'c') {
        /* error to specify a sign */
        if (format->sign != '\0') {
            PyErr_SetString(PyExc_ValueError,
                            "Sign not allowed with integer"
                            " format specifier 'c'");
            goto done;
        }
        /* error to request alternate format */
        if (format->alternate) {
            PyErr_SetString(PyExc_ValueError,
                            "Alternate form (#) not allowed with integer"
                            " format specifier 'c'");
            goto done;
        }

        /* taken from unicodeobject.c formatchar() */
        /* Integer input truncated to a character */
        x = PyLong_AsLong(value);
        if (x == -1 && PyErr_Occurred())
            goto done;
        if (x < 0 || x > 0x10ffff) {
            PyErr_SetString(PyExc_OverflowError,
                            "%c arg not in range(0x110000)");
            goto done;
        }
        tmp = PyUnicode_FromOrdinal(x);
        inumeric_chars = 0;
        n_digits = 1;
        maxchar = Py_MAX(maxchar, (Py_UCS4)x);

        /* As a sort-of hack, we tell calc_number_widths that we only
           have "remainder" characters. calc_number_widths thinks
           these are characters that don't get formatted, only copied
           into the output string. We do this for 'c' formatting,
           because the characters are likely to be non-digits. */
        n_remainder = 1;
    }
    else {
        int base;
        int leading_chars_to_skip = 0;  /* Number of characters added by
                                           PyNumber_ToBase that we want to
                                           skip over. */

        /* Compute the base and how many characters will be added by
           PyNumber_ToBase */
        switch (format->type) {
        case 'b':
            base = 2;
            leading_chars_to_skip = 2; /* 0b */
            break;
        case 'o':
            base = 8;
            leading_chars_to_skip = 2; /* 0o */
            break;
        case 'x':
        case 'X':
            base = 16;
            leading_chars_to_skip = 2; /* 0x */
            break;
        default:  /* shouldn't be needed, but stops a compiler warning */
        case 'd':
        case 'n':
            base = 10;
            break;
        }

        if (format->sign != '+' && format->sign != ' '
                && format->width == -1
//.........这里部分代码省略.........
开发者ID:CabbageHead-360,项目名称:cpython,代码行数:101,代码来源:formatter_unicode.c


示例9: pygts_vertex_from_sequence

PygtsVertex *
pygts_vertex_from_sequence(PyObject *tuple) {
  guint i,N;
  gdouble x=0,y=0,z=0;
  PyObject *obj;
  GtsVertex *v;
  PygtsVertex *vertex;

  /* Convert list into tuple */
  if(PyList_Check(tuple)) {
    tuple = PyList_AsTuple(tuple);
  }
  else {
    Py_INCREF(tuple);
  }
  if(!PyTuple_Check(tuple)) {
    Py_DECREF(tuple);
    PyErr_SetString(PyExc_TypeError,"expected a list or tuple of vertices");
    return NULL;
  }

  /* Get the tuple size */
  if( (N = PyTuple_Size(tuple)) > 3 ) {
    PyErr_SetString(PyExc_RuntimeError,
		    "expected a list or tuple of up to three floats");
    Py_DECREF(tuple);
    return NULL;
  }

  /* Get the coordinates */
  for(i=0;i<N;i++) {
    obj = PyTuple_GET_ITEM(tuple,i);

    if(!PyFloat_Check(obj) && !PyLong_Check(obj)) {
      PyErr_SetString(PyExc_TypeError,"expected a list or tuple of floats");
      Py_DECREF(tuple);
      return NULL;
    }
    if(i==0) {
      if(PyFloat_Check(obj)) x = PyFloat_AsDouble(obj);
      else  x = (double)PyLong_AsLong(obj);
    }
    if(i==1) {
      if(PyFloat_Check(obj)) y = PyFloat_AsDouble(obj);
      else  y = (double)PyLong_AsLong(obj);
    }
    if(i==2) {
      if(PyFloat_Check(obj)) z = PyFloat_AsDouble(obj);
      else  z = (double)PyLong_AsLong(obj);
    }
  }
  Py_DECREF(tuple);

  /* Create the vertex */  
  if( (v = gts_vertex_new(gts_vertex_class(),x,y,z)) == NULL ) {
    PyErr_SetString(PyExc_MemoryError,"could not create Vertex");
  }
  if( (vertex = pygts_vertex_new(v)) == NULL ) {
    gts_object_destroy(GTS_OBJECT(v));
    return NULL;
  }

  return vertex;
}
开发者ID:Azeko2xo,项目名称:woodem,代码行数:64,代码来源:vertex.cpp


示例10: Py2MI

std::shared_ptr<MI::MIValue> Py2MI(PyObject* pyValue, MI_Type valueType)
{
    if (pyValue == Py_None)
    {
        return std::make_shared<MI::MIValue>(valueType);
    }
    if (PyObject_IsInstance(pyValue, reinterpret_cast<PyObject*>(&PyBool_Type)))
    {
        return MI::MIValue::FromBoolean(PyObject_IsTrue(pyValue) ? MI_TRUE : MI_FALSE);
    }
    else if (PyObject_IsInstance(pyValue, reinterpret_cast<PyObject*>(&PyLong_Type)))
    {
        switch (valueType)
        {
        case MI_BOOLEAN:
            return MI::MIValue::FromBoolean(PyLong_AsLong(pyValue) != 0);
        case MI_UINT8:
            return MI::MIValue::FromUint8((MI_Uint8)PyLong_AsUnsignedLong(pyValue));
        case MI_SINT8:
            return MI::MIValue::FromSint8((MI_Sint8)PyLong_AsLong(pyValue));
        case MI_UINT16:
            return MI::MIValue::FromUint16((MI_Uint16)PyLong_AsUnsignedLong(pyValue));
        case MI_SINT16:
            return MI::MIValue::FromSint16((MI_Sint16)PyLong_AsLong(pyValue));
        case MI_CHAR16:
            return MI::MIValue::FromChar16((MI_Char16)PyLong_AsLong(pyValue));
        case MI_UINT32:
            return MI::MIValue::FromUint32(PyLong_AsUnsignedLong(pyValue));
        case MI_SINT32:
            return MI::MIValue::FromSint32(PyLong_AsLong(pyValue));
        case MI_UINT64:
            return MI::MIValue::FromUint64(PyLong_AsUnsignedLongLong(pyValue));
        case MI_SINT64:
            return MI::MIValue::FromSint64(PyLong_AsLongLong(pyValue));
        case MI_REAL32:
            return MI::MIValue::FromReal32((MI_Real32)PyLong_AsDouble(pyValue));
        case MI_REAL64:
            return MI::MIValue::FromReal64(PyLong_AsDouble(pyValue));
        case MI_STRING:
            return Py2StrMIValue(pyValue);
        default:
            throw MI::TypeConversionException();
        }
    }
#ifndef IS_PY3K
    else if (PyObject_IsInstance(pyValue, reinterpret_cast<PyObject*>(&PyInt_Type)))
    {
        switch (valueType)
        {
        case MI_BOOLEAN:
            return MI::MIValue::FromBoolean(PyInt_AsLong(pyValue) != 0);
        case MI_UINT8:
            return MI::MIValue::FromUint8((MI_Uint8)PyInt_AsLong(pyValue));
        case MI_SINT8:
            return MI::MIValue::FromSint8((MI_Sint8)PyInt_AsLong(pyValue));
        case MI_UINT16:
            return MI::MIValue::FromUint16((MI_Uint16)PyInt_AsLong(pyValue));
        case MI_SINT16:
            return MI::MIValue::FromSint16((MI_Sint16)PyInt_AsLong(pyValue));
        case MI_CHAR16:
            return MI::MIValue::FromChar16((MI_Char16)PyLong_AsLong(pyValue));
        case MI_UINT32:
            return MI::MIValue::FromUint32((MI_Uint32)PyInt_AsLong(pyValue));
        case MI_SINT32:
            return MI::MIValue::FromSint32((MI_Sint32)PyInt_AsLong(pyValue));
        case MI_UINT64:
            return MI::MIValue::FromUint64((MI_Uint64)PyInt_AsLong(pyValue));
        case MI_SINT64:
            return MI::MIValue::FromSint64((MI_Sint64)PyInt_AsLong(pyValue));
        case MI_REAL32:
            return MI::MIValue::FromReal32((MI_Real32)PyInt_AsLong(pyValue));
        case MI_REAL64:
            return MI::MIValue::FromReal64((MI_Real64)PyInt_AsLong(pyValue));
        case MI_STRING:
            return Py2StrMIValue(pyValue);
        default:
            throw MI::TypeConversionException();
        }
    }
    else if (PyObject_IsInstance(pyValue, reinterpret_cast<PyObject*>(&PyString_Type)))
    {
        switch (valueType)
        {
        case MI_STRING:
            return MI::MIValue::FromString(std::string(PyString_AsString(pyValue)));
        case MI_SINT8:
        case MI_UINT8:
        case MI_SINT16:
        case MI_UINT16:
        case MI_CHAR16:
        case MI_SINT32:
        case MI_UINT32:
        case MI_SINT64:
        case MI_UINT64:
        case MI_REAL32:
        case MI_REAL64:
            return Str2PyLong2MI(PyString_AsString(pyValue), valueType);
        default:
            throw MI::TypeConversionException();
        }
//.........这里部分代码省略.........
开发者ID:alinbalutoiu,项目名称:PyMI,代码行数:101,代码来源:Utils.cpp


示例11: PyMember_SetOne

int
PyMember_SetOne(char *addr, PyMemberDef *l, PyObject *v)
{
	PyObject *oldv;

	if ((l->flags & READONLY) || l->type == T_STRING
#ifdef macintosh
	    || l->type == T_PSTRING
#endif
		)
	{
		PyErr_SetString(PyExc_TypeError, "readonly attribute");
		return -1;
	}
	//	if ((l->flags & WRITE_RESTRICTED) && PyEval_GetRestricted()) {
	//		PyErr_SetString(PyExc_RuntimeError, "restricted attribute");
	//		return -1;
	//	}
	if (v == NULL && l->type != T_OBJECT_EX && l->type != T_OBJECT) {
		PyErr_SetString(PyExc_TypeError,
				"can't delete numeric/char attribute");
		return -1;
	}
	addr += l->offset;
	switch (l->type) {
	case T_BYTE:
	case T_UBYTE:
		if (!PyInt_Check(v)) {
			PyErr_BadArgument();
			return -1;
		}
		*(char*)addr = (char) PyInt_AsLong(v);
		break;
	case T_SHORT:
	case T_USHORT:
		if (!PyInt_Check(v)) {
			PyErr_BadArgument();
			return -1;
		}
		*(short*)addr = (short) PyInt_AsLong(v);
		break;
	case T_UINT:
	case T_INT:
		if (!PyInt_Check(v)) {
			PyErr_BadArgument();
			return -1;
		}
		*(int*)addr = (int) PyInt_AsLong(v);
		break;
	case T_LONG:
		if (!PyInt_Check(v)) {
			PyErr_BadArgument();
			return -1;
		}
		*(long*)addr = PyInt_AsLong(v);
		break;
	case T_ULONG:
		if (PyInt_Check(v))
			*(long*)addr = PyInt_AsLong(v);
		else if (PyLong_Check(v))
			*(long*)addr = PyLong_AsLong(v);
		else {
			PyErr_BadArgument();
			return -1;
		}
		break;
	case T_FLOAT:
		if (PyInt_Check(v))
			*(float*)addr =
				(float) PyInt_AsLong(v);
		else if (PyFloat_Check(v))
			*(float*)addr =
				(float) PyFloat_AsDouble(v);
		else {
			PyErr_BadArgument();
			return -1;
		}
		break;
	case T_DOUBLE:
		if (PyInt_Check(v))
			*(double*)addr = (double) PyInt_AsLong(v);
		else if (PyFloat_Check(v))
			*(double*)addr = PyFloat_AsDouble(v);
		else {
			PyErr_BadArgument();
			return -1;
		}
		break;
	case T_OBJECT:
	case T_OBJECT_EX:
		Py_XINCREF(v);
		oldv = *(PyObject **)addr;
		*(PyObject **)addr = v;
		Py_XDECREF(oldv);
		break;
	case T_CHAR:
		if (PyString_Check(v) && PyString_Size(v) == 1) {
			*(char*)addr = PyString_AsString(v)[0];
		}
		else {
//.........这里部分代码省略.........
开发者ID:MatiasNAmendola,项目名称:cleese,代码行数:101,代码来源:structmember.c


示例12: EdgeNature_from_BPy_Nature

Nature::EdgeNature EdgeNature_from_BPy_Nature(PyObject *obj)
{
	return static_cast<Nature::EdgeNature>(PyLong_AsLong(obj));
}
开发者ID:Andrewson3D,项目名称:blender-for-vray,代码行数:4,代码来源:BPy_Convert.cpp


示例13: MediumType_from_BPy_MediumType

Stroke::MediumType MediumType_from_BPy_MediumType(PyObject *obj)
{
	return static_cast<Stroke::MediumType>(PyLong_AsLong(obj));
}
开发者ID:Andrewson3D,项目名称:blender-for-vray,代码行数:4,代码来源:BPy_Convert.cpp


示例14: IntegrationType_from_BPy_IntegrationType

IntegrationType IntegrationType_from_BPy_IntegrationType(PyObject *obj)
{
	return static_cast<IntegrationType>(PyLong_AsLong(obj));
}
开发者ID:Andrewson3D,项目名称:blender-for-vray,代码行数:4,代码来源:BPy_Convert.cpp


示例15: ufunc_fromfunc

PyObject *
ufunc_fromfunc(PyObject *NPY_UNUSED(dummy), PyObject *args) {

    // unsigned long func_address; // unused
    int nin, nout;
    int nfuncs, ntypes, ndata;
    PyObject *func_list;
    PyObject *type_list;
    PyObject *data_list;
    PyObject *func_obj;
    PyObject *type_obj;
    PyObject *data_obj;
    PyObject *object=NULL; /* object to hold on to while ufunc is alive */
    PyObject *dispatcher = NULL;

    int i, j;
    int custom_dtype = 0;
    PyUFuncGenericFunction *funcs;
    int *types;
    void **data;
    PyObject *ufunc;

    if (!PyArg_ParseTuple(args, "O!O!iiO|OO", &PyList_Type, &func_list,
                                               &PyList_Type, &type_list,
                                               &nin, &nout, &data_list,
                                               &dispatcher,
                                               &object)) {
        return NULL;
    }

    if (dispatcher == Py_None)
        dispatcher = NULL;

    nfuncs = PyList_Size(func_list);

    ntypes = PyList_Size(type_list);
    if (ntypes != nfuncs) {
        PyErr_SetString(PyExc_TypeError, "length of types list must be same as length of function pointer list");
        return NULL;
    }

    ndata = PyList_Size(data_list);
    if (ndata != nfuncs) {
        PyErr_SetString(PyExc_TypeError, "length of data pointer list must be same as length of function pointer list");
        return NULL;
    }

    funcs = PyArray_malloc(nfuncs * sizeof(PyUFuncGenericFunction));
    if (funcs == NULL) {
        return NULL;
    }

    /* build function pointer array */
    for (i = 0; i < nfuncs; i++) {
        func_obj = PyList_GetItem(func_list, i);
        /* Function pointers are passed in as long objects.
           Is there a better way to do this? */
        if (PyLong_Check(func_obj)) {
            funcs[i] = (PyUFuncGenericFunction)PyLong_AsVoidPtr(func_obj);
        }
        else {
            PyErr_SetString(PyExc_TypeError, "function pointer must be long object, or None");
            return NULL;
        }
    }

    types = PyArray_malloc(nfuncs * (nin+nout) * sizeof(int));
    if (types == NULL) {
        return NULL;
    }

    /* build function signatures array */
    for (i = 0; i < nfuncs; i++) {
        type_obj = PyList_GetItem(type_list, i);
        if (!type_obj)
            return NULL;

        for (j = 0; j < (nin+nout); j++) {
            int dtype_num;
            PyObject *dtype_num_obj = PyList_GetItem(type_obj, j);
            if (!dtype_num_obj)
                return NULL;

            SENTRY_VALID_LONG(
                types[i*(nin+nout) + j] = PyLong_AsLong(dtype_num_obj)
            );

            dtype_num = PyLong_AsLong(PyList_GetItem(type_obj, j));

            SENTRY_VALID_LONG(dtype_num);

            if (dtype_num >= NPY_USERDEF) {
                custom_dtype = dtype_num;
            }
        }
    }

    data = PyArray_malloc(nfuncs * sizeof(void *));
    if (data == NULL) {
        return NULL;
//.........这里部分代码省略.........
开发者ID:ASPP,项目名称:numba,代码行数:101,代码来源:_ufunc.c


示例16: KX_GetActiveScene

int BL_ArmatureConstraint::py_attr_setattr(void *self_v, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
{
	BL_ArmatureConstraint* self = static_cast<BL_ArmatureConstraint*>(self_v);
	bConstraint* constraint = self->m_constraint;
	bKinematicConstraint* ikconstraint = (constraint && constraint->type == CONSTRAINT_TYPE_KINEMATIC) ? (bKinematicConstraint*)constraint->data : NULL;
	int attr_order = attrdef-Attributes;
	int ival;
	double dval;
//	char* sval;
	SCA_LogicManager *logicmgr = KX_GetActiveScene()->GetLogicManager();
	KX_GameObject *oval;

	if (!constraint) {
		PyErr_SetString(PyExc_AttributeError, "constraint is NULL");
		return PY_SET_ATTR_FAIL;
	}

	switch (attr_order) {
	case BCA_ENFORCE:
		dval = PyFloat_AsDouble(value);
		if (dval < 0.0 || dval > 1.0) { /* also accounts for non float */
			PyErr_SetString(PyExc_AttributeError, "constraint.enforce = float: BL_ArmatureConstraint, expected a float between 0 and 1");
			return PY_SET_ATTR_FAIL;
		}
		constraint->enforce = dval;
		return PY_SET_ATTR_SUCCESS;

	case BCA_HEADTAIL:
		dval = PyFloat_AsDouble(value);
		if (dval < 0.0 || dval > 1.0) { /* also accounts for non float */
			PyErr_SetString(PyExc_AttributeError, "constraint.headtail = float: BL_ArmatureConstraint, expected a float between 0 and 1");
			return PY_SET_ATTR_FAIL;
		}
		constraint->headtail = dval;
		return PY_SET_ATTR_SUCCESS;

	case BCA_TARGET:
		if (!ConvertPythonToGameObject(logicmgr, value, &oval, true, "constraint.target = value: BL_ArmatureConstraint"))
			return PY_SET_ATTR_FAIL; // ConvertPythonToGameObject sets the error
		self->SetTarget(oval);
		return PY_SET_ATTR_SUCCESS;

	case BCA_SUBTARGET:
		if (!ConvertPythonToGameObject(logicmgr, value, &oval, true, "constraint.subtarget = value: BL_ArmatureConstraint"))
			return PY_SET_ATTR_FAIL; // ConvertPythonToGameObject sets the error
		self->SetSubtarget(oval);
		return PY_SET_ATTR_SUCCESS;

	case BCA_ACTIVE:
		ival = PyObject_IsTrue( value );
		if (ival == -1) {
			PyErr_SetString(PyExc_AttributeError, "constraint.active = bool: BL_ArmatureConstraint, expected True or False");
			return PY_SET_ATTR_FAIL;
		}
		self->m_constraint->flag = (self->m_constraint->flag & ~CONSTRAINT_OFF) | ((ival)?0:CONSTRAINT_OFF);
		return PY_SET_ATTR_SUCCESS;

	case BCA_IKWEIGHT:
	case BCA_IKDIST:
	case BCA_IKMODE:
		if (!ikconstraint) {
			PyErr_SetString(PyExc_AttributeError, "constraint is not of IK type");
			return PY_SET_ATTR_FAIL;
		}
		switch (attr_order) {
		case BCA_IKWEIGHT:
			dval = PyFloat_AsDouble(value);
			if (dval < 0.0 || dval > 1.0) { /* also accounts for non float */
				PyErr_SetString(PyExc_AttributeError, "constraint.weight = float: BL_ArmatureConstraint, expected a float between 0 and 1");
				return PY_SET_ATTR_FAIL;
			}
			ikconstraint->weight = dval;
			return PY_SET_ATTR_SUCCESS;

		case BCA_IKDIST:
			dval = PyFloat_AsDouble(value);
			if (dval < 0.0) {  /* also accounts for non float */
				PyErr_SetString(PyExc_AttributeError, "constraint.ik_dist = float: BL_ArmatureConstraint, expected a positive float");
				return PY_SET_ATTR_FAIL;
			}
			ikconstraint->dist = dval;
			return PY_SET_ATTR_SUCCESS;

		case BCA_IKMODE:
			ival = PyLong_AsLong(value);
			if (ival < 0) {
				PyErr_SetString(PyExc_AttributeError, "constraint.ik_mode = integer: BL_ArmatureConstraint, expected a positive integer");
				return PY_SET_ATTR_FAIL;
			}
			ikconstraint->mode = ival;
			return PY_SET_ATTR_SUCCESS;
		}
		// should not come here
		break;

	}

	PyErr_SetString(PyExc_AttributeError, "constraint unknown attribute");
	return PY_SET_ATTR_FAIL;
}
开发者ID:Ichthyostega,项目名称:blender,代码行数:100,代码来源:BL_ArmatureConstraint.cpp


示例17: scribus_setproperty

PyObject* scribus_setproperty(PyObject* /*self*/, PyObject* args, PyObject* kw)
{
	PyObject* objArg = NULL;
	char* propertyName = NULL;
	PyObject* objValue = NULL;
	char* kwargs[] = {const_cast<char*>("object"),
					  const_cast<char*>("property"),
					  const_cast<char*>("value"),
					  NULL};
	if (!PyArg_ParseTupleAndKeywords(args, kw, "OesO", kwargs,
				&objArg, "ascii", &propertyName, &objValue))
		return NULL;

	// We're going to hang on to the value object for a while, so
	// claim a reference to it.
	Py_INCREF(objValue);

	// Get the QObject* the object argument refers to
	QObject* obj = getQObjectFromPyArg(objArg);
	if (!obj)
		return NULL;
	objArg = NULL; // no need to decref, it's borrowed

	const char* propertyTypeName = getpropertytype(obj, propertyName, true);
	if (propertyTypeName == NULL)
		return NULL;
	QString propertyType = QString::fromLatin1(propertyTypeName);

	// Did we know how to convert the value argument to the right type?
	bool matched = false;
	// Did the set call succceed?
	bool success = false;

	// Check the C++ type of the property, and try to convert the passed
	// PyObject to something sensible looking for it.
	// FIXME: handle enums/sets
	// NUMERIC TYPES
	// These are unfortuately a TOTAL PITA because of the multitude of
	// C and Python numeric types. TODO This needs to be broken out into a subroutine.
	if (propertyType == "bool")
	{
		match 

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C++ PyLong_AsLongLong函数代码示例发布时间:2022-05-30
下一篇:
C++ PyLong_AsDouble函数代码示例发布时间:2022-05-30
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap