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

C++ PyString_FromStringAndSize函数代码示例

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

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



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

示例1: switch


//.........这里部分代码省略.........
		case VT_CY:
			return PyObject_FromCurrency(pVar->cyVal);
		case VT_CY|VT_VECTOR:
			return VectorToSeq<CY>(pVar->cacy.pElems, pVar->cacy.cElems, PyObject_FromCurrency);
		case VT_DATE:
			return PyWinObject_FromDATE(pVar->date);
		case VT_DATE|VT_VECTOR:
			return VectorToSeq(pVar->cadate.pElems, pVar->cadate.cElems, PyWinObject_FromDATE);
		case VT_BSTR:
			return PyWinObject_FromBstr(pVar->bstrVal);
		case VT_BSTR|VT_VECTOR:
			return VectorToSeq(pVar->cabstr.pElems, pVar->cabstr.cElems, PyWinObject_FromVT_BSTR);
		case VT_BOOL:
			return PyWinObject_FromVARIANT_BOOL(pVar->boolVal);
		case VT_BOOL|VT_VECTOR:
			return VectorToSeq(pVar->cabool.pElems, pVar->cabool.cElems, PyWinObject_FromVARIANT_BOOL);
		case VT_ERROR:
			return PyInt_FromLong(pVar->scode);
		case VT_ERROR|VT_VECTOR:
			return VectorToSeq(pVar->cascode.pElems, pVar->cascode.cElems, PyInt_FromLong);
		case VT_FILETIME:
			return PyWinObject_FromFILETIME(pVar->filetime);
		case VT_FILETIME|VT_VECTOR:
			return VectorToSeq<FILETIME>(pVar->cafiletime.pElems, pVar->cafiletime.cElems, PyWinObject_FromFILETIME);
		case VT_LPSTR:
			if (pVar->pszVal == NULL) {
				Py_INCREF(Py_None);
				return Py_None;
			}
			return PyWinCoreString_FromString(pVar->pszVal);
		case VT_LPSTR|VT_VECTOR:
			{
				PyObject *ret = PyList_New(pVar->calpstr.cElems);
				if (ret==NULL) return NULL;
				for (ULONG i=0; i<pVar->calpstr.cElems;i++){
					PyObject *elem=PyWinCoreString_FromString(pVar->calpstr.pElems[i]);
					if (elem==NULL){
						Py_DECREF(ret);
						return NULL;
						}
					PyList_SET_ITEM(ret, i, elem);
					}
				return ret;
			}
		case VT_LPWSTR:
			return PyWinObject_FromOLECHAR(pVar->pwszVal);
		case VT_LPWSTR|VT_VECTOR:
			{
				PyObject *ret = PyList_New(pVar->calpwstr.cElems);
				if (ret==NULL) return NULL;
				for (ULONG i=0; i<pVar->calpwstr.cElems;i++){
					PyObject *elem=PyWinObject_FromWCHAR(pVar->calpwstr.pElems[i]);
					if (elem==NULL){
						Py_DECREF(ret);
						return NULL;
						}
					PyList_SET_ITEM(ret, i, elem);
					}
				return ret;
			}
		case VT_CLSID:
			return PyWinObject_FromIID(*pVar->puuid);
		case VT_CLSID|VT_VECTOR:
			return VectorToSeq<CLSID>(pVar->cauuid.pElems, pVar->cauuid.cElems, PyWinObject_FromIID);
		case VT_STREAM:
		case VT_STREAMED_OBJECT:
			return PyCom_PyObjectFromIUnknown(pVar->pStream, IID_IStream, TRUE);
		case VT_STORAGE:
		case VT_STORED_OBJECT:
			return PyCom_PyObjectFromIUnknown(pVar->pStorage, IID_IStorage, TRUE);
		case VT_VECTOR | VT_VARIANT:
			return PyObject_FromPROPVARIANTs(pVar->capropvar.pElems, pVar->capropvar.cElems);
		case VT_BLOB:
		case VT_BLOB_OBJECT:
			return PyString_FromStringAndSize((const char *)pVar->blob.pBlobData,
			                                  pVar->blob.cbSize);
//		case VT_UNKNOWN:
//			return PyCom_PyObjectFromIUnknown(pVar->punkVal, IID_IUnknown, TRUE);
//		case VT_DISPATCH:
//			return PyCom_PyObjectFromIUnknown(pVar->pdispVal, IID_IDispatch, TRUE);

/*
// Want to get VT_CF and VT_BLOB working with a test case first!
		case VT_CF: { // special "clipboard format"
			// cbSize is the size of the buffer pointed to 
			// by pClipData, plus sizeof(ulClipFmt)
			// XXX - in that case, shouldn't we pass
			// pClipData + sizeof(DWORD) to Py_BuildValue??
			ULONG cb = CBPCLIPDATA(*pVar->pclipdata);
			return Py_BuildValue("is#",
			                     pVar->pclipdata->ulClipFmt,
			                     pVar->pclipdata->pClipData,
			                     (int)cb);
			}
*/
		default:
			PyErr_Format(PyExc_TypeError, "Unsupported property type 0x%x", pVar->vt);
			return NULL;
	}
}
开发者ID:malrsrch,项目名称:pywin32,代码行数:101,代码来源:PyIPropertyStorage.cpp


示例2: PyZlib_flush

static PyObject *
PyZlib_flush(compobject *self, PyObject *args)
{
    int err, length = DEFAULTALLOC;
    PyObject *RetVal;
    int flushmode = Z_FINISH;
    unsigned long start_total_out;

    if (!PyArg_ParseTuple(args, "|i:flush", &flushmode))
	return NULL;

    /* Flushing with Z_NO_FLUSH is a no-op, so there's no point in
       doing any work at all; just return an empty string. */
    if (flushmode == Z_NO_FLUSH) {
	return PyString_FromStringAndSize(NULL, 0);
    }

    if (!(RetVal = PyString_FromStringAndSize(NULL, length)))
	return NULL;

    ENTER_ZLIB

    start_total_out = self->zst.total_out;
    self->zst.avail_in = 0;
    self->zst.avail_out = length;
    self->zst.next_out = (unsigned char *)PyString_AS_STRING(RetVal);

    Py_BEGIN_ALLOW_THREADS
    err = deflate(&(self->zst), flushmode);
    Py_END_ALLOW_THREADS

    /* while Z_OK and the output buffer is full, there might be more output,
       so extend the output buffer and try again */
    while (err == Z_OK && self->zst.avail_out == 0) {
	if (_PyString_Resize(&RetVal, length << 1) < 0)
	    goto error;
	self->zst.next_out = (unsigned char *)PyString_AS_STRING(RetVal) \
	    + length;
	self->zst.avail_out = length;
	length = length << 1;

	Py_BEGIN_ALLOW_THREADS
	err = deflate(&(self->zst), flushmode);
	Py_END_ALLOW_THREADS
    }

    /* If flushmode is Z_FINISH, we also have to call deflateEnd() to free
       various data structures. Note we should only get Z_STREAM_END when
       flushmode is Z_FINISH, but checking both for safety*/
    if (err == Z_STREAM_END && flushmode == Z_FINISH) {
	err = deflateEnd(&(self->zst));
	if (err != Z_OK) {
	    zlib_error(self->zst, err, "from deflateEnd()");
	    Py_DECREF(RetVal);
	    RetVal = NULL;
	    goto error;
	}
	else
	    self->is_initialised = 0;

	/* We will only get Z_BUF_ERROR if the output buffer was full
	   but there wasn't more output when we tried again, so it is
	   not an error condition.
	*/
    } else if (err!=Z_OK && err!=Z_BUF_ERROR) {
	zlib_error(self->zst, err, "while flushing");
	Py_DECREF(RetVal);
	RetVal = NULL;
	goto error;
    }

    _PyString_Resize(&RetVal, self->zst.total_out - start_total_out);

 error:
    LEAVE_ZLIB

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


示例3: PyErr_Format

PyObject *Client_gets(PyClient *self, PyObject *args)
{
    //[ ] def gets(self, key, default = None):

    char *pKey;
    size_t cbKey;
    char *pData;
    size_t cbData;
    UINT64 cas;
    int flags;

    if (!PyArg_ParseTuple (args, "s#", &pKey, &cbKey))
    {
        return NULL;
    }

    self->client->getsBegin();

    self->client->getKeyWrite(pKey, cbKey);
    self->client->getFlush();

    bool bError = false;

    if (!self->client->getReadNext(&pKey, &cbKey, &pData, &cbData, &flags, &cas, &bError))
    {
        if (bError)
        {
            if (!PyErr_Occurred())
            {
                return PyErr_Format(PyExc_RuntimeError, "umemcached: %s", self->client->getError());
            }
            return NULL;
        }

        Py_RETURN_NONE;
    }



    PyObject *otuple = PyTuple_New(3);
    PyObject *ovalue = PyString_FromStringAndSize(pData, cbData);
    PyObject *oflags = PyInt_FromLong(flags);
    PyObject *ocas = PyLong_FromUnsignedLongLong(cas);

    PyTuple_SET_ITEM(otuple, 0, ovalue);
    PyTuple_SET_ITEM(otuple, 1, oflags);
    PyTuple_SET_ITEM(otuple, 2, ocas);

    while (self->client->getReadNext(&pKey, &cbKey, &pData, &cbData, &flags, &cas, &bError));

    if (bError)
    {
        Py_DECREF(otuple);

        if (!PyErr_Occurred())
        {
            return PyErr_Format(PyExc_RuntimeError, "umemcached: %s", self->client->getError());
        }

        return NULL;
    }

    return otuple;
}
开发者ID:sreekanth-anubolu,项目名称:ultramemcached,代码行数:64,代码来源:umemcached.cpp


示例4: fixup_ulcase

static void
fixup_ulcase(void)
{
    PyObject *mods, *strop, *string, *ulo;
    unsigned char ul[256];
    int n, c;

    /* find the string and strop modules */
    mods = PyImport_GetModuleDict();
    if (!mods)
        return;
    string = PyDict_GetItemString(mods, "string");
    if (string)
        string = PyModule_GetDict(string);
    strop=PyDict_GetItemString(mods, "strop");
    if (strop)
        strop = PyModule_GetDict(strop);
    if (!string && !strop)
        return;

    /* create uppercase map string */
    n = 0;
    for (c = 0; c < 256; c++) {
        if (isupper(c))
            ul[n++] = c;
    }
    ulo = PyString_FromStringAndSize((const char *)ul, n);
    if (!ulo)
        return;
    if (string)
        PyDict_SetItemString(string, "uppercase", ulo);
    if (strop)
        PyDict_SetItemString(strop, "uppercase", ulo);
    Py_DECREF(ulo);

    /* create lowercase string */
    n = 0;
    for (c = 0; c < 256; c++) {
        if (islower(c))
            ul[n++] = c;
    }
    ulo = PyString_FromStringAndSize((const char *)ul, n);
    if (!ulo)
        return;
    if (string)
        PyDict_SetItemString(string, "lowercase", ulo);
    if (strop)
        PyDict_SetItemString(strop, "lowercase", ulo);
    Py_DECREF(ulo);

    /* create letters string */
    n = 0;
    for (c = 0; c < 256; c++) {
        if (isalpha(c))
            ul[n++] = c;
    }
    ulo = PyString_FromStringAndSize((const char *)ul, n);
    if (!ulo)
        return;
    if (string)
        PyDict_SetItemString(string, "letters", ulo);
    Py_DECREF(ulo);
}
开发者ID:grobe0ba,项目名称:plan9front,代码行数:63,代码来源:_localemodule.c


示例5: PyZlib_decompress

static PyObject *
PyZlib_decompress(PyObject *self, PyObject *args)
{
    PyObject *result_str;
    Byte *input;
    int length, err;
    int wsize=DEF_WBITS, r_strlen=DEFAULTALLOC;
    z_stream zst;

    if (!PyArg_ParseTuple(args, "s#|ii:decompress",
			  &input, &length, &wsize, &r_strlen))
	return NULL;

    if (r_strlen <= 0)
	r_strlen = 1;

    zst.avail_in = length;
    zst.avail_out = r_strlen;

    if (!(result_str = PyString_FromStringAndSize(NULL, r_strlen)))
	return NULL;

    zst.zalloc = (alloc_func)NULL;
    zst.zfree = (free_func)Z_NULL;
    zst.next_out = (Byte *)PyString_AS_STRING(result_str);
    zst.next_in = (Byte *)input;
    err = inflateInit2(&zst, wsize);

    switch(err) {
    case(Z_OK):
	break;
    case(Z_MEM_ERROR):
	PyErr_SetString(PyExc_MemoryError,
			"Out of memory while decompressing data");
	goto error;
    default:
        inflateEnd(&zst);
	zlib_error(zst, err, "while preparing to decompress data");
	goto error;
    }

    do {
	Py_BEGIN_ALLOW_THREADS
	err=inflate(&zst, Z_FINISH);
	Py_END_ALLOW_THREADS

	switch(err) {
	case(Z_STREAM_END):
	    break;
	case(Z_BUF_ERROR):
	    /*
	     * If there is at least 1 byte of room according to zst.avail_out
	     * and we get this error, assume that it means zlib cannot
	     * process the inflate call() due to an error in the data.
	     */
	    if (zst.avail_out > 0) {
		PyErr_Format(ZlibError, "Error %i while decompressing data",
			     err);
		inflateEnd(&zst);
		goto error;
	    }
	    /* fall through */
	case(Z_OK):
	    /* need more memory */
	    if (_PyString_Resize(&result_str, r_strlen << 1) < 0) {
		inflateEnd(&zst);
		goto error;
	    }
	    zst.next_out = (unsigned char *)PyString_AS_STRING(result_str) \
		+ r_strlen;
	    zst.avail_out = r_strlen;
	    r_strlen = r_strlen << 1;
	    break;
	default:
	    inflateEnd(&zst);
	    zlib_error(zst, err, "while decompressing data");
	    goto error;
	}
    } while (err != Z_STREAM_END);

    err = inflateEnd(&zst);
    if (err != Z_OK) {
	zlib_error(zst, err, "while finishing data decompression");
	goto error;
    }

    _PyString_Resize(&result_str, zst.total_out);
    return result_str;

 error:
    Py_XDECREF(result_str);
    return NULL;
}
开发者ID:Oize,项目名称:pspstacklesspython,代码行数:93,代码来源:zlibmodule.c


示例6: parse_multi_line_message

static int parse_multi_line_message(Request* request, const char* data, const size_t data_len){  
    char *newline = NULL;
    int pos = 0, ok;
    long long ll;
    int partialdone = 0;

    if (request->parse_phase == RDS_PHASE_CONNECT){
        if (request->multibulklen == 0) {        
            newline = strchr(data,'\r');
            if (newline == NULL) {
                // if (sdslen(c->querybuf) > REDIS_INLINE_MAX_SIZE) {
                //     addReplyError(c,"Protocol error: too big mbulk count string");
                //     setProtocolError(c,0);
                // }

                // we will come back here,                
                return -1;
            }

            ok = string2ll(data+1, newline-(data+1), &ll);
            if (!ok || ll > 1024*1024) {
                puts("couldnt find data length... ");
                return -2;
            }
            pos = (newline - data)+2;

            if (ll <= 0) {
                // TODO: handle *-1\r\n ?
                // c->querybuf = sdsrange(c->querybuf,pos,-1);
                return true;
            }        

            request->cmd_list = PyList_New(ll);

            request->multibulklen = ll;     
            request->arg_cnt = 0;   
            request->parse_phase = RDS_PHASE_START;
            // now send the remainder to start line...
            request->lastpos = pos;                        
        }
    }    
    

    while (request->multibulklen){        
        // since we found the start line, here we parse it...
        if (request->parse_phase == RDS_PHASE_START){      
              if (data[request->lastpos] == '$'){
                      // 
                      newline = strchr(data+request->lastpos,'\r');
                      if (!newline){
                        return -1;
                      }

                      ok = string2ll(data+request->lastpos+1, newline - (data+ request->lastpos+1),&ll);
                      if (!ok || ll < 0 || ll > 512*1024*1024) {
                          return -2;
                      }

                        // now parse data line...            
                        pos = (newline - data)+2;

                        if (ll < 0) {
                            // handle $-1\r\n ?
                            // protocol error !!!
                            // c->querybuf = sdsrange(c->querybuf,pos,-1);                
                            return -2;
                        }

                        // now send the remainder to start line...
                        request->lastpos = pos;                
                        request->parse_phase = RDS_PHASE_DATA;
                        request->bulklen = ll;
              } else {
                puts("ERR: protocol error");
                return -2;
              }
          }
          // 
          if (request->parse_phase == RDS_PHASE_DATA){      

                if ((int)(data_len - request->lastpos) < 0){
                  return -1;
                }

                // do we have enough data ???
                if ( (int)(data_len - request->lastpos) < (int)(request->bulklen+2)) {
                    /* Not enough data (+2 == trailing \r\n) */                    
                    return -1;
                    break;
                } else {                                        
                    char *str2 = malloc(request->bulklen + 1);
                    memcpy(str2, data + request->lastpos, request->bulklen);                  
                    str2[request->bulklen] = '\0';

                    PyObject* str = PyString_FromStringAndSize(str2, request->bulklen);                  
                    PyList_SetItem(request->cmd_list, request->arg_cnt++, str);                   
                    // NOTE: as far as i understand, PyList_SetItem doesnt incref
                    // http://stackoverflow.com/questions/3512414/does-this-pylist-appendlist-py-buildvalue-leak
                    // Py_DECREF(str); <- TODO: why ? if i do this weird things happen
                    free(str2);                  
//.........这里部分代码省略.........
开发者ID:ybrs,项目名称:the-giant,代码行数:101,代码来源:request.c


示例7: PyObject_IsTrue

static PyObject *py_parse_tree(PyObject *self, PyObject *args, PyObject *kw)
{
	char *text, *start, *end;
	int len, namelen, strict;
	PyObject *ret, *item, *name, *sha, *py_strict = NULL;
	static char *kwlist[] = {"text", "strict", NULL};

	if (!PyArg_ParseTupleAndKeywords(args, kw, "s#|O", kwlist,
	                                 &text, &len, &py_strict))
		return NULL;
	strict = py_strict ?  PyObject_IsTrue(py_strict) : 0;
	/* TODO: currently this returns a list; if memory usage is a concern,
	 * consider rewriting as a custom iterator object */
	ret = PyList_New(0);
	if (ret == NULL) {
		return NULL;
	}
	start = text;
	end = text + len;
	while (text < end) {
		long mode;
		if (strict && text[0] == '0') {
			PyErr_SetString(object_format_exception_cls,
			                "Illegal leading zero on mode");
			Py_DECREF(ret);
			return NULL;
		}
		mode = strtol(text, &text, 8);
		if (*text != ' ') {
			PyErr_SetString(PyExc_ValueError, "Expected space");
			Py_DECREF(ret);
			return NULL;
		}
		text++;
		namelen = strnlen(text, len - (text - start));
		name = PyString_FromStringAndSize(text, namelen);
		if (name == NULL) {
			Py_DECREF(ret);
			return NULL;
		}
		if (text + namelen + 20 >= end) {
			PyErr_SetString(PyExc_ValueError, "SHA truncated");
			Py_DECREF(ret);
			Py_DECREF(name);
			return NULL;
		}
		sha = sha_to_pyhex((unsigned char *)text+namelen+1);
		if (sha == NULL) {
			Py_DECREF(ret);
			Py_DECREF(name);
			return NULL;
		}
		item = Py_BuildValue("(NlN)", name, mode, sha);
		if (item == NULL) {
			Py_DECREF(ret);
			Py_DECREF(sha);
			Py_DECREF(name);
			return NULL;
		}
		if (PyList_Append(ret, item) == -1) {
			Py_DECREF(ret);
			Py_DECREF(item);
			return NULL;
		}
		Py_DECREF(item);
		text += namelen+21;
	}
	return ret;
}
开发者ID:justinvh,项目名称:dulwich,代码行数:69,代码来源:_objects.c


示例8: tns_parse_string

static void*
tns_parse_string(const tns_ops *ops, const char *data, size_t len)
{
  return PyString_FromStringAndSize(data, len);
}
开发者ID:pombredanne,项目名称:tnetstring,代码行数:5,代码来源:_tnetstring.c


示例9: Py_BuildValue

PyObject *build_property( const unicap_property_t *property )
{
   PyObject *obj = NULL;
   PyObject *tmp = NULL;
   
   // name: string, category: string, unit: string, (value: float)|(menu_item: string), 
   // (range: (float,float))|(values:[float,..])|(menu:[string,..]), flags: [string], capabilities: [string]

   obj = Py_BuildValue( "{s:s,s:s}", 
			"identifier", property->identifier, 
			"category", property->category );
   if( !obj )
   {
      return NULL;
   }
   
   if( strlen( property->unit ) > 0 )
   {
      if( PyDict_SetItemString( obj, "unit", Py_BuildValue( "s", property->unit ) ) != 0 )
	 goto err;
   }

   switch( property->type )
   {
      case UNICAP_PROPERTY_TYPE_RANGE:
      {
	 if( PyDict_SetItemString( obj, "value", Py_BuildValue( "d", property->value ) ) != 0 )
	    goto err;
	 if( PyDict_SetItemString( obj, "range", Py_BuildValue( "(d,d)", property->range.min, property->range.max ) ) != 0 )
	    goto err;
      }
      break;
      case UNICAP_PROPERTY_TYPE_VALUE_LIST:
      {
	 int i;
/* 	 if( !property->value_list ) */
/* 	    goto err; */

	 if( PyDict_SetItemString( obj, "value", Py_BuildValue( "d", property->value ) ) != 0 )
	    goto err;
	 tmp = PyList_New(0);
	 if( !tmp )
	    goto err;
	 for( i = 0; i < property->value_list.value_count; i++ )
	 {
	    if( PyList_Append( tmp, Py_BuildValue( "d", property->value_list.values[i] ) ) != 0 )
	       goto err;
	 }
	 if( PyDict_SetItemString( obj, "values", tmp ) )
	    goto err;

	 tmp = NULL;
      }
      break;
      
      case UNICAP_PROPERTY_TYPE_MENU:
      {
	 int i;
	 if( PyDict_SetItemString( obj, "menu_item", Py_BuildValue( "s", property->menu_item ) ) != 0 )
	    goto err;
	 
	 tmp = PyList_New(0);
	 if( !tmp) 
	    goto err;
	 
	 for( i = 0; i < property->menu.menu_item_count; i++ )
	 {
	    if( PyList_Append( tmp, Py_BuildValue( "s", property->menu.menu_items[i] ) ) != 0 )
	       goto err;
	 }
	 if( PyDict_SetItemString( obj, "menu_items", tmp ) )
	    goto err;

	 tmp = NULL;
      }
      break;

   case UNICAP_PROPERTY_TYPE_DATA:
   {
      PyObject *data = PyString_FromStringAndSize( (char*)property->property_data, property->property_data_size );
      PyDict_SetItemString( obj, "data", data );
   }
   break;
   
      
      default:
	 break;
   }
   
   tmp = build_property_flags_list( property->flags );
   if( !tmp )
      goto err;
   if( PyDict_SetItemString( obj, "flags", tmp ) != 0 )
      goto err;
   
   tmp = build_property_flags_list( property->flags_mask );
   if( !tmp )
      goto err;
   if( PyDict_SetItemString( obj, "flags_mask", tmp ) != 0 )
      goto err;
//.........这里部分代码省略.........
开发者ID:gabrielduque,项目名称:unicap-1,代码行数:101,代码来源:utils.c


示例10: PyString_FromString


//.........这里部分代码省略.........
            value = Py_None;
            Py_INCREF(value);
        }
        goto cleanup;
    }
    
    // check for server
    Py_DECREF(temp);
    temp = PyString_FromString("server");
    if (PyObject_Cmp(temp, name, &result) == -1)
        goto cleanup;
    if (result == 0) {
        if (pyuser->silcobj->server)
            value = PyString_FromString(pyuser->silcobj->server);
        else {
            value = Py_None;
            Py_INCREF(value);
        }
        goto cleanup;
    }    
  
    // check for realname
    Py_DECREF(temp);
    temp = PyString_FromString("realname");
    if (PyObject_Cmp(temp, name, &result) == -1)
        goto cleanup;
    if (result == 0) {
        if (pyuser->silcobj->realname)
            value = PyString_FromString(pyuser->silcobj->realname);
        else {
            value = Py_None;
            Py_INCREF(value);
        }
        goto cleanup;
    }
    
    // check for fingerprint
    Py_DECREF(temp);
    temp = PyString_FromString("fingerprint");
    if (PyObject_Cmp(temp, name, &result) == -1)
        goto cleanup;
    if (result == 0) {
        if (pyuser->silcobj->fingerprint)
            value = PyString_FromStringAndSize(pyuser->silcobj->fingerprint, pyuser->silcobj->fingerprint_len);
        else {
            value = Py_None;
            Py_INCREF(value);
        }
        goto cleanup;
    }
  
    // check for user id
    Py_DECREF(temp);
    temp = PyString_FromString("user_id");
    if (PyObject_Cmp(temp, name, &result) == -1)
        goto cleanup;
    if (result == 0) {
        char buf[224];
        memcpy(&buf, (pyuser->silcobj->id), 224);
        value = PyString_FromStringAndSize(buf, 224);
        goto cleanup;
    }
    
    // check for mode
    Py_DECREF(temp);
    temp = PyString_FromString("mode");
    if (PyObject_Cmp(temp, name, &result) == -1)
        goto cleanup;
    if (result == 0) {
        value = PyInt_FromLong(pyuser->silcobj->mode);
        goto cleanup;
    }
    
    // check for status
    Py_DECREF(temp);
    temp = PyString_FromString("status");
    if (PyObject_Cmp(temp, name, &result) == -1)
        goto cleanup;
    if (result == 0) {
        value = PyInt_FromLong(pyuser->silcobj->status);
        goto cleanup;
    }
    
    // check for resolve_cmd_ident
    Py_DECREF(temp);
    temp = PyString_FromString("resolve_cmd_ident");
    if (PyObject_Cmp(temp, name, &result) == -1)
        goto cleanup;
    if (result == 0) {
        value = PyInt_FromLong(pyuser->silcobj->resolve_cmd_ident);
        goto cleanup;
    }
    
cleanup:
    Py_XDECREF(temp);
    if (value)
        return value;
    else
        return PyObject_GenericGetAttr(self, name);    
}
开发者ID:BackupTheBerlios,项目名称:python-silc-svn,代码行数:101,代码来源:pysilc_user.c


示例11: printf

static PyObject *texture_sample(PyObject *self, PyObject *args)
{
/*
  sample part of texture, args:
  whole texture as string, width and height
  output texture width and height
  upper lext and lower right corbers of rectangle from whole texture to be sampled into output texture
  
*/
  long int textureWidth, textureHeight;
  long int screenWidth, screenHeight;
  int i;
  int textureLen;
  char *texture;
  char *result;
  int resultSize;
  char *resPtr;
  double x1,y1,x2,y2;
  double dx,dy;
  double texturey,texturex;
  int y,x,posy,posx;
  PyObject *pyRes;
  if (!PyArg_ParseTuple(args, "s#lllldddd",
                        &texture, &textureLen,
                        &textureWidth, &textureHeight,
                        &screenWidth, &screenHeight,
                        &x1, &y1, &x2, &y2))
    return NULL;
  resultSize = screenWidth*screenHeight*3;
/*
  printf("%li, %li, %li, %li, %g, %g, %g, %g (%i)\n",
         textureWidth, textureHeight,
         screenWidth, screenHeight,
         x1,y1,x2,y2,
         resultSize);
*/
  resPtr = result = malloc(resultSize);
  if(!resPtr) return NULL;
  dx = (x2-x1)/screenWidth;
  dy = (y2-y1)/screenHeight;
  //printf("d: %g,%g\n", dx,dy);
  texturey = y1;
  for(y=0; y<screenHeight; y++, texturey+=dy) {
    if(texturey<0.0 || texturey>=textureHeight) {
      for(x=0; x<screenWidth*3; x++, resPtr++) {
        *resPtr = -1;
      }
    } else {
      posy = (int)texturey * textureWidth*3;
      texturex = x1;
      for(x=0; x<screenWidth; x++, texturex+=dx) {
        if(texturex<0.0 || texturex>=textureWidth) {
          for(i=0; i<3; i++, resPtr++) *resPtr = -1;
        } else {
          posx = posy + (int)texturex*3;
          for(i=0; i<3; i++, resPtr++) {
            *resPtr = texture[posx+i];
            //printf("%i,%i %g,%g: %i\n", y,x, texturey, texturex, (int)texture[posx+i]);
          }
        }
      }
    }
  }
  //printf("...done\n");
  
  pyRes = PyString_FromStringAndSize(result, resultSize);
  free(result);
  return pyRes;
}
开发者ID:worldforge,项目名称:atlas-cpp,代码行数:69,代码来源:texturemodule.c


示例12: captureObject_next

PyObject *
captureObject_next(captureObject *self)
{
    u_char *packet = NULL;
    struct pcap_pkthdr header;
    PyObject *ethernet = NULL;
    PyObject *result = NULL;
    PyObject *resultTuple = NULL;
    ethernet_t *eth_header = NULL;
    char buffer[255];
    double packetTime;
    int packet_offset = 0;
    PyObject *remaining = NULL;
    int offset[5] = {
        0, 0, 0, 0, 0
    };
    

    packet = (u_char *) pcap_next(self->pcap, &header);
    if (! packet)
    {
        Py_INCREF(Py_None);
        return Py_None;

        //        PyErr_SetString(ErrorObject, "No data available before timeout");
        //        return NULL;
    }
    sprintf(buffer, "%ld.%ld", (long) header.ts.tv_sec, (long) header.ts.tv_usec);
    packetTime = strtod(buffer, NULL);
    result = PyList_New(0);
    switch (pcap_datalink(self->pcap))
    {
        case DLT_EN10MB:
        {
            eth_header = (ethernet_t *) packet;
            ethernet = (PyObject *) PyProtocol_newEthernetObjectFromPacket(eth_header, &packet_offset);
            offset[0] = packet_offset;
            PyList_Append(result, ethernet);
            Py_DECREF(ethernet);

            switch (ntohs(eth_header->ether_type))
            {
                case ETHERTYPE_IP:
                {
                    if (! parseIP(result, header, packet, &packet_offset))
                    {
                        Py_DECREF(result);
                        return NULL;
                    }
                    offset[1] = packet_offset;
                    break;
                }
                case ETHERTYPE_ARP:
                    if (! parseARP(result, header, packet, &packet_offset))
                    {
                        Py_DECREF(result);
                        return NULL;
                    }
                    offset[2] = packet_offset;
                    break;
                default:
                {
                    
                }
            }
            break;
        }
        case DLT_NULL:
        {
            packet_offset = 4;
            if (! parseIP(result, header, packet, &packet_offset))
            {
                Py_DECREF(result);
                return NULL;
            }
            offset[3] = packet_offset;
            break;
        }
    }
    if ((int) (header.len) - packet_offset < 0)
    {
        Py_DECREF(result);
        PyErr_Format(ErrorObject, "Parsed parsed end of packet (%d %d %d %d)",
                        offset[0], offset[1], offset[2], offset[3]);
        return NULL;
    }
    remaining = PyString_FromStringAndSize((char *) (packet + packet_offset),
                                                     header.len - packet_offset);
    PyList_Append(result, remaining);
    Py_DECREF(remaining);
    
    
    PyList_Append(result, PyFloat_FromDouble(packetTime));
    resultTuple = PyList_AsTuple(result);
    Py_DECREF(result);
    return resultTuple;
}
开发者ID:Aliced3645,项目名称:DataCenterMarketing,代码行数:97,代码来源:capturemodule.c


示例13: PyErr_SetString

static PyObject *_filter_read(filterobject *self, PyObject *args, int readline)
{

    apr_bucket *b;
    long bytes_read;
    PyObject *result;
    char *buffer;
    long bufsize;
    int newline = 0;
    long len = -1;
    conn_rec *c = self->request_obj->request_rec->connection;

    if (! PyArg_ParseTuple(args, "|l", &len)) 
        return NULL;

    if (self->closed) {
        PyErr_SetString(PyExc_ValueError, "I/O operation on closed filter");
        return NULL;
    }

    if (self->is_input) {

        /* does the output brigade exist? */
        if (!self->bb_in) {
            self->bb_in = apr_brigade_create(self->f->r->pool, 
                                             c->bucket_alloc);
        }

        Py_BEGIN_ALLOW_THREADS;
        self->rc = ap_get_brigade(self->f->next, self->bb_in, self->mode, 
                                  APR_BLOCK_READ, self->readbytes);
        Py_END_ALLOW_THREADS;

        if (!APR_STATUS_IS_EAGAIN(self->rc) && !(self->rc == APR_SUCCESS)) {
            PyErr_SetObject(PyExc_IOError, 
                            PyString_FromString("Input filter read error"));
            return NULL;
        }
    }

    /* 
     * loop through the brigade reading buckets into the string 
     */

    b = APR_BRIGADE_FIRST(self->bb_in);

    if (b == APR_BRIGADE_SENTINEL(self->bb_in))
        return PyString_FromString("");

    /* reached eos ? */
    if (APR_BUCKET_IS_EOS(b)) {
        apr_bucket_delete(b);
        Py_INCREF(Py_None);
        return Py_None;
    }

    bufsize = len < 0 ? HUGE_STRING_LEN : len;
    /* PYTHON 2.5: 'PyString_FromStringAndSize' uses Py_ssize_t for input parameters */ 
    result = PyString_FromStringAndSize(NULL, bufsize);

    /* possibly no more memory */
    if (result == NULL) 
        return PyErr_NoMemory();
    
    buffer = PyString_AS_STRING((PyStringObject *) result);

    bytes_read = 0;

    while ((bytes_read < len || len == -1) && 
           !(APR_BUCKET_IS_EOS(b) || APR_BUCKET_IS_FLUSH(b) ||
             b == APR_BRIGADE_SENTINEL(self->bb_in))) {

        const char *data;
        apr_size_t size;
        apr_bucket *old;
        int i;

        if (apr_bucket_read(b, &data, &size, APR_BLOCK_READ) != APR_SUCCESS) {
            PyErr_SetObject(PyExc_IOError, 
                            PyString_FromString("Filter read error"));
            return NULL;
        }

        if (bytes_read + size > bufsize) {
            apr_bucket_split(b, bufsize - bytes_read);
            size = bufsize - bytes_read;
            /* now the bucket is the exact size we need */
        }

        if (readline) {

            /* scan for newline */
            for (i=0; i<size; i++) {
                if (data[i] == '\n') {
                    if (i+1 != size) {   /* (no need to split if we're at end of bucket) */
                        
                        /* split after newline */
                        apr_bucket_split(b, i+1);   
                        size = i + 1;
                    }
//.........这里部分代码省略.........
开发者ID:go-juice,项目名称:mod_python,代码行数:101,代码来源:filterobject.c


示例14: PyCode_Optimize


//.........这里部分代码省略.........
                if (!UNCONDITIONAL_JUMP(codestr[tgt]))
                    continue;
                tgttgt = GETJUMPTGT(codestr, tgt);
                if (opcode == JUMP_FORWARD) /* JMP_ABS can go backwards */
                    opcode = JUMP_ABSOLUTE;
                if (!ABSOLUTE_JUMP(opcode))
                    tgttgt -= i + 3;     /* Calc relative jump addr */
                if (tgttgt < 0)                           /* No backward relative jumps */
                    continue;
                codestr[i] = opcode;
                SETARG(codestr, i, tgttgt);
                break;

            case EXTENDED_ARG:
                goto exitUnchanged;

                /* Replace RETURN LOAD_CONST None RETURN with just RETURN */
                /* Remove unreachable JUMPs after RETURN */
            case RETURN_VALUE:
                if (i+4 >= codelen)
                    continue;
                if (codestr[i+4] == RETURN_VALUE &&
                    ISBASICBLOCK(blocks,i,5))
                    memset(codestr+i+1, NOP, 4);
                else if (UNCONDITIONAL_JUMP(codestr[i+1]) &&
                         ISBASICBLOCK(blocks,i,4))
                    memset(codestr+i+1, NOP, 3);
                break;
        }
    }

    /* Fixup linenotab */
    for (i=0, nops=0 ; i<codelen ; i += CODESIZE(codestr[i])) {
        addrmap[i] = i - nops;
        if (codestr[i] == NOP)
            nops++;
    }
    cum_orig_line = 0;
    last_line = 0;
    for (i=0 ; i < tabsiz ; i+=2) {
        cum_orig_line += lineno[i];
        new_line = addrmap[cum_orig_line];
        assert (new_line - last_line < 255);
        lineno[i] =((unsigned char)(new_line - last_line));
        last_line = new_line;
    }

    /* Remove NOPs and fixup jump targets */
    for (i=0, h=0 ; i<codelen ; ) {
        opcode = codestr[i];
        switch (opcode) {
            case NOP:
                i++;
                continue;

            case JUMP_ABSOLUTE:
            case CONTINUE_LOOP:
            case POP_JUMP_IF_FALSE:
            case POP_JUMP_IF_TRUE:
            case JUMP_IF_FALSE_OR_POP:
            case JUMP_IF_TRUE_OR_POP:
                j = addrmap[GETARG(codestr, i)];
                SETARG(codestr, i, j);
                break;

            case FOR_ITER:
            case JUMP_FORWARD:
            case SETUP_LOOP:
            case SETUP_EXCEPT:
            case SETUP_FINALLY:
            case SETUP_WITH:
                j = addrmap[GETARG(codestr, i) + i + 3] - addrmap[i] - 3;
                SETARG(codestr, i, j);
                break;
        }
        adj = CODESIZE(opcode);
        while (adj--)
            codestr[h++] = codestr[i++];
    }
    assert(h + nops == codelen);

    code = PyString_FromStringAndSize((char *)codestr, h);
    PyMem_Free(addrmap);
    PyMem_Free(codestr);
    PyMem_Free(blocks);
    return code;

 exitError:
    code = NULL;

 exitUnchanged:
    if (blocks != NULL)
        PyMem_Free(blocks);
    if (addrmap != NULL)
        PyMem_Free(addrmap);
    if (codestr != NULL)
        PyMem_Free(codestr);
    Py_XINCREF(code);
    return code;
}
开发者ID:AbnerChang,项目名称:edk2-staging,代码行数:101,代码来源:peephole.c


示例15: decode_string

static PyObject*
decode_string(JSONData *jsondata)
{
    PyObject *object;
    int c, escaping, has_unicode, string_escape;
    Py_ssize_t len;
    char *ptr;

    // look for the closing quote
    escaping = has_unicode = string_escape = False;
    ptr = jsondata->ptr + 1;
    while (True) {
        c = *ptr;
        if (c == 0) {
            PyErr_Format(JSON_DecodeError,
                         "unterminated string starting at position " SSIZE_T_F,
                         (Py_ssize_t)(jsondata->ptr - jsondata->str));
            return NULL;
        }
        if (!escaping) {
            if (c == '\\') {
                escaping = True;
            } else if (c == '"') {
                break;
            } else if (!isascii(c)) {
                has_unicode = True;
            }
        } else {
            switch(c) {
            case 'u':
                has_unicode = True;
                break;
            case '"':
            case 'r':
            case 'n':
            case 't':
            case 'b':
            case 'f':
            case '\\':
                string_escape = True;
                break;
            }
            escaping = False;
        }
        ptr++;
    }

    len = ptr - jsondata->ptr - 1;

    if (has_unicode || jsondata->all_unicode)
        object = PyUnicode_DecodeUnicodeEscape(jsondata->ptr+1, len, NULL);
    else if (string_escape)
        object = PyString_DecodeEscape(jsondata->ptr+1, len, NULL, 0, NULL);
    else
        object = PyString_FromStringAndSize(jsondata->ptr+1, len);

    if (object == NULL) {
        PyObject *type, *value, *tb, *reason;

        PyErr_Fetch(&type, &value, &tb);
        if (type == NULL) {
            PyErr_Format(JSON_DecodeError,
                         "invalid string starting at position " SSIZE_T_F,
                         (Py_ssize_t)(jsondata->ptr - jsondata->str));
        } else {
            if (PyErr_GivenExceptionMatches(type, PyExc_UnicodeDecodeError)) {
                reason = PyObject_GetAttrString(value, "reason");
                PyErr_Format(JSON_DecodeError, "cannot decode string starting"
                             " at position " SSIZE_T_F ": %s",
                             (Py_ssize_t)(jsondata->ptr - jsondata->str),
                             reason ? PyString_AsString(reason) : "bad format");
                Py_XDECREF(reason);
            } else {
                PyErr_Format(JSON_DecodeError,
                             "invalid string starting at position " SSIZE_T_F,
                             (Py_ssize_t)(jsondata->ptr - jsondata->str));
            }
        }
        Py_XDECREF(type);
        Py_XDECREF(value);
        Py_XDECREF(tb);
    } else {
        jsondata->ptr = ptr+1;
    }

    return object;
}
开发者ID:petronius,项目名称:cjsonx,代码行数:87,代码来源:cjsonx.c


示例16: csl_execute

int
csl_execute(char *code, size_t size, const char *func_name, struct pack *pak, char **resptr, int *reslen)
{
	PyObject *pCode, *pModule, *pDict, *pFunc, *pValue, *pStr;
	PyObject *pArgs, *pkArgs;
	PyMethodDef *meth;
	node *n;

	pModule = PyImport_AddModule("__builtin__");
	pDict = PyModule_GetDict(pModule);
	for (meth = methods; meth->ml_name; meth++) {
		pCode = PyCFunction_New(meth, NULL);
		PyDict_SetItemString(pDict, meth->ml_name, pCode);
	}

	if (size == 0) {
		n = PyParser_SimpleParseString(code, Py_file_input);
		if (!n) {
			log_exception();
			return CSL_BADCODE;
		}
		pCode = (PyObject *) PyNode_Compile(n, "lala");
		PyNode_Free(n);
		if (!pCode) {
			log_exception();
			return CSL_BADCODE;
		}
	} else {
		pCode = PyMarshal_ReadObjectFromString(code, size);
		if (!pCode) {
			log_exception();
			return CSL_BADCODE;
		}
	}
	pModule = PyImport_ExecCodeModule("csl", pCode);
	Py_DECREF(pCode);

	if (!pModule || !PyModule_Check(pModule)) {
		return CSL_BADCODE;
	}

	pDict = PyModule_GetDict(pModule);
	if (!pDict) {
		Py_DECREF(pModule);
		return CSL_BADCODE;
	}

	pFunc = PyDict_GetItemString(pDict, func_name);
	if (!pFunc || !PyCallable_Check(pFunc)) {
		Py_DECREF(pModule);
		return CSL_NOFUNC;
	}

	pArgs = NULL;
	pkArgs = PyDict_New();
	while (pak) {
		PyObject *p;
		char *t, *t2;
		size_t sz;
		if (pack_get(pak, &t, &sz) == 0) break;
		if (pack_get(pak, &t2, &sz) == 0) {
			pArgs = PyTuple_New(1);
			PyTuple_SetItem(pArgs, 0, PyString_FromString(t));
			Py_DECREF(pkArgs);
			break;
		}
		p = PyString_FromStringAndSize(t2, sz);
		PyDict_SetItemString(pkArgs, t, p);
	}
	if (!pArgs) pArgs = PyTuple_New(0);

	pValue = PyObject_Call(pFunc, pArgs, pkArgs);
	if (!pValue) {
		log_exception();
		Py_DECREF(pModule);
		return CSL_FUNCERR;
	}

	pStr = PyObject_Str(pValue);

	Py_DECREF(pValue);
	Py_DECREF(pModule);

	// is return value asked?
	if (resptr == NULL) return 0;

	*reslen = PyString_Size(pStr);
	*resptr = malloc((*reslen) + 1);
	if (!*resptr) {
		Py_DECREF(pStr);
		return CSL_NOMEM;
	}
	memcpy(*resptr, PyString_AsString(pStr), *reslen);
	(*resptr)[*reslen] = '\0';

	return 0;
}
开发者ID:Tayyib,项目名称:uludag,代码行数:97,代码来源:csl.c


示例17: decode_number

static PyObject*
decode_number(JSONData *jsondata)
{
    PyObject *object, *str;
    int c, is_float, should_stop;
    char *ptr;

    // check if  

鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
C++ PyString_GET_SIZE函数代码示例发布时间:2022-05-30
下一篇:
C++ PyString_FromFormat函数代码示例发布时间: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