本文整理汇总了C++中Py_INCREF函数的典型用法代码示例。如果您正苦于以下问题:C++ Py_INCREF函数的具体用法?C++ Py_INCREF怎么用?C++ Py_INCREF使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了Py_INCREF函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: SqlNVarChar_init
static int SqlNVarChar_init(PyObject* self, PyObject* args, PyObject* kwargs)
{
const char* utf8bytes = NULL;
size_t nutf8bytes = 0;
PyObject* encoded;
enum TdsType tdstype;
PyObject* unicode = NULL;
size_t nchars = 0;
Py_ssize_t size = (Py_ssize_t)-1;
static char* s_kwlist[] =
{
"value",
"size",
NULL
};
/* Z# would be ideal here, but is not supported prior to Python 3. */
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O|n", s_kwlist, &unicode, &size))
{
return -1;
}
if (Py_None == unicode)
{
/* `None` passed as argument. */
encoded = PyTuple_GET_ITEM(args, 0);
Py_INCREF(encoded);
utf8bytes = NULL;
}
else if (PyUnicode_Check(unicode))
{
encoded = encode_for_dblib(unicode, &utf8bytes, &nutf8bytes, &nchars);
if (!encoded)
{
return -1;
}
}
else
{
PyErr_SetObject(PyExc_TypeError, unicode);
return -1;
}
/*
FreeTDS doesn't have good support for NCHAR types prior
to 0.95. Fallback to VARCHAR with somewhat crippled
functionality.
*/
#if defined(CTDS_USE_NCHARS)
tdstype = (nchars > TDS_NCHAR_MAX_SIZE) ? TDSNTEXT : TDSNVARCHAR;
#else /* if defined(CTDS_USE_NCHARS) */
tdstype = (nchars > TDS_CHAR_MAX_SIZE) ? TDSTEXT : TDSVARCHAR;
#endif /* else if defined(CTDS_USE_NCHARS) */
SqlType_init_variable(self,
encoded,
tdstype,
/*
If the size is not explicitly specified, infer it from the value.
The NVARCHAR type size must be >= 1.
*/
(int)MAX(1, (((Py_ssize_t)-1 == size) ? nchars : (size_t)size)),
(void*)utf8bytes,
nutf8bytes,
NULL);
Py_DECREF(encoded);
return 0;
}
示例2: do_mkvalue
static PyObject* do_mkvalue(const char** p_format, va_list* p_va, int flags) noexcept {
for (;;) {
switch (*(*p_format)++) {
case '(':
return do_mktuple(p_format, p_va, ')', countformat(*p_format, ')'), flags);
case '[':
return do_mklist(p_format, p_va, ']', countformat(*p_format, ']'), flags);
case '{':
return do_mkdict(p_format, p_va, '}', countformat(*p_format, '}'), flags);
case 'b':
case 'B':
case 'h':
case 'i':
return PyInt_FromLong((long)va_arg(*p_va, int));
case 'H':
return PyInt_FromLong((long)va_arg(*p_va, unsigned int));
case 'I': {
unsigned int n;
n = va_arg(*p_va, unsigned int);
if (n > (unsigned long)PyInt_GetMax())
return PyLong_FromUnsignedLong((unsigned long)n);
else
return PyInt_FromLong(n);
}
case 'n':
#if SIZEOF_SIZE_T != SIZEOF_LONG
return PyInt_FromSsize_t(va_arg(*p_va, Py_ssize_t));
#endif
/* Fall through from 'n' to 'l' if Py_ssize_t is long */
case 'l':
return PyInt_FromLong(va_arg(*p_va, long));
case 'd':
return PyFloat_FromDouble(va_arg(*p_va, double));
case 'N':
case 'S':
case 'O':
if (**p_format == '&') {
typedef PyObject* (*converter)(void*);
converter func = va_arg(*p_va, converter);
void* arg = va_arg(*p_va, void*);
++*p_format;
return (*func)(arg);
} else {
PyObject* v;
v = va_arg(*p_va, PyObject*);
if (v != NULL) {
if (*(*p_format - 1) != 'N')
Py_INCREF(v);
} else if (!PyErr_Occurred())
/* If a NULL was passed
* because a call that should
* have constructed a value
* failed, that's OK, and we
* pass the error on; but if
* no error occurred it's not
* clear that the caller knew
* what she was doing. */
PyErr_SetString(PyExc_SystemError, "NULL object passed to Py_BuildValue");
return v;
}
case 's':
case 'z': {
PyObject* v;
char* str = va_arg(*p_va, char*);
Py_ssize_t n;
if (**p_format == '#') {
++*p_format;
if (flags & FLAG_SIZE_T)
n = va_arg(*p_va, Py_ssize_t);
else
n = va_arg(*p_va, int);
} else
n = -1;
if (str == NULL) {
v = Py_None;
Py_INCREF(v);
} else {
if (n < 0) {
size_t m = strlen(str);
if (m > PY_SSIZE_T_MAX) {
PyErr_SetString(PyExc_OverflowError, "string too long for Python string");
return NULL;
}
n = (Py_ssize_t)m;
}
v = PyString_FromStringAndSize(str, n);
}
return v;
}
示例3: initofx
//.........这里部分代码省略.........
if (PyType_Ready(&PyOFXRectDType) < 0)
{
std::cerr << "Failed to intiialize ofx.RectD class" << std::endl;
Py_DECREF(mod);
return;
}
INIT_TYPE(PyOFXRangeIType, "ofx.RangeI", PyOFXRangeI);
PyOFXRangeIType.tp_flags = Py_TPFLAGS_DEFAULT;
PyOFXRangeIType.tp_new = PyOFXRangeI_New;
PyOFXRangeIType.tp_init = PyOFXRangeI_Init;
PyOFXRangeIType.tp_dealloc = PyOFXRangeI_Delete;
PyOFXRangeIType.tp_getset = PyOFXRangeI_GetSeters;
if (PyType_Ready(&PyOFXRangeIType) < 0)
{
std::cerr << "Failed to intiialize ofx.RangeI class" << std::endl;
Py_DECREF(mod);
return;
}
INIT_TYPE(PyOFXRangeDType, "ofx.RangeD", PyOFXRangeD);
PyOFXRangeDType.tp_flags = Py_TPFLAGS_DEFAULT;
PyOFXRangeDType.tp_new = PyOFXRangeD_New;
PyOFXRangeDType.tp_init = PyOFXRangeD_Init;
PyOFXRangeDType.tp_dealloc = PyOFXRangeD_Delete;
PyOFXRangeDType.tp_getset = PyOFXRangeD_GetSeters;
if (PyType_Ready(&PyOFXRangeDType) < 0)
{
std::cerr << "Failed to intiialize ofx.RangeD class" << std::endl;
Py_DECREF(mod);
return;
}
Py_INCREF(&PyOFXActionArgumentsType);
PyModule_AddObject(mod, "ActionArguments", (PyObject*)&PyOFXActionArgumentsType);
Py_INCREF(&PyOFXRectIType);
PyModule_AddObject(mod, "RectI", (PyObject*)&PyOFXRectIType);
Py_INCREF(&PyOFXRectDType);
PyModule_AddObject(mod, "RectD", (PyObject*)&PyOFXRectDType);
Py_INCREF(&PyOFXRangeIType);
PyModule_AddObject(mod, "RangeI", (PyObject*)&PyOFXRangeIType);
Py_INCREF(&PyOFXRangeDType);
PyModule_AddObject(mod, "RangeD", (PyObject*)&PyOFXRangeDType);
Py_INCREF(&PyOFXRangeDType);
PyModule_AddObject(mod, "FrameRange", (PyObject*)&PyOFXRangeDType);
if (!PyOFX_InitException(mod))
{
std::cerr << "Failed to intiialize exception classes" << std::endl;
Py_DECREF(mod);
return;
}
if (!PyOFX_InitHandle(mod))
{
std::cerr << "Failed to intiialize handle classes" << std::endl;
Py_DECREF(mod);
return;
}
if (!PyOFX_InitPixel(mod))
示例4: __pyx_tp_clear_5cache_Cache
static int __pyx_tp_clear_5cache_Cache(PyObject *o) {
struct __pyx_obj_5cache_Cache *p = (struct __pyx_obj_5cache_Cache *)o;
Py_XDECREF(p->list);
p->list = Py_None; Py_INCREF(p->list);
return 0;
}
示例5: AddRef
PyObject* AddRef() {
if(p) {
Py_INCREF(p);
}
return p;
}
示例6: CField_FromDesc
//.........这里部分代码省略.........
*pfield_size = 0;
}
size = dict->size;
length = dict->length;
proto = desc;
/* Field descriptors for 'c_char * n' are be scpecial cased to
return a Python string instead of an Array object instance...
*/
if (ArrayTypeObject_Check(proto)) {
StgDictObject *adict = PyType_stgdict(proto);
StgDictObject *idict;
if (adict && adict->proto) {
idict = PyType_stgdict(adict->proto);
if (!idict) {
PyErr_SetString(PyExc_TypeError,
"has no _stginfo_");
Py_DECREF(self);
return NULL;
}
if (idict->getfunc == getentry("c")->getfunc) {
struct fielddesc *fd = getentry("s");
getfunc = fd->getfunc;
setfunc = fd->setfunc;
}
#ifdef CTYPES_UNICODE
if (idict->getfunc == getentry("u")->getfunc) {
struct fielddesc *fd = getentry("U");
getfunc = fd->getfunc;
setfunc = fd->setfunc;
}
#endif
}
}
self->setfunc = setfunc;
self->getfunc = getfunc;
self->index = index;
Py_INCREF(proto);
self->proto = proto;
switch (fieldtype) {
case NEW_BITFIELD:
if (big_endian)
self->size = (bitsize << 16) + *pfield_size - *pbitofs - bitsize;
else
self->size = (bitsize << 16) + *pbitofs;
*pbitofs = bitsize;
/* fall through */
case NO_BITFIELD:
if (pack)
align = min(pack, dict->align);
else
align = dict->align;
if (align && *poffset % align) {
Py_ssize_t delta = align - (*poffset % align);
*psize += delta;
*poffset += delta;
}
if (bitsize == 0)
self->size = size;
*psize += size;
self->offset = *poffset;
*poffset += size;
*palign = align;
break;
case EXPAND_BITFIELD:
*poffset += dict->size - *pfield_size/8;
*psize += dict->size - *pfield_size/8;
*pfield_size = dict->size * 8;
if (big_endian)
self->size = (bitsize << 16) + *pfield_size - *pbitofs - bitsize;
else
self->size = (bitsize << 16) + *pbitofs;
self->offset = *poffset - size; /* poffset is already updated for the NEXT field */
*pbitofs += bitsize;
break;
case CONT_BITFIELD:
if (big_endian)
self->size = (bitsize << 16) + *pfield_size - *pbitofs - bitsize;
else
self->size = (bitsize << 16) + *pbitofs;
self->offset = *poffset - size; /* poffset is already updated for the NEXT field */
*pbitofs += bitsize;
break;
}
return (PyObject *)self;
}
示例7: structseq_new
static PyObject *
structseq_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
PyObject *arg = NULL;
PyObject *dict = NULL;
PyObject *ob;
PyStructSequence *res = NULL;
Py_ssize_t len, min_len, max_len, i, n_unnamed_fields;
static char *kwlist[] = {"sequence", "dict", 0};
if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:structseq",
kwlist, &arg, &dict))
return NULL;
arg = PySequence_Fast(arg, "constructor requires a sequence");
if (!arg) {
return NULL;
}
if (dict && !PyDict_Check(dict)) {
PyErr_Format(PyExc_TypeError,
"%.500s() takes a dict as second arg, if any",
type->tp_name);
Py_DECREF(arg);
return NULL;
}
len = PySequence_Fast_GET_SIZE(arg);
min_len = VISIBLE_SIZE_TP(type);
max_len = REAL_SIZE_TP(type);
n_unnamed_fields = UNNAMED_FIELDS_TP(type);
if (min_len != max_len) {
if (len < min_len) {
PyErr_Format(PyExc_TypeError,
"%.500s() takes an at least %zd-sequence (%zd-sequence given)",
type->tp_name, min_len, len);
Py_DECREF(arg);
return NULL;
}
if (len > max_len) {
PyErr_Format(PyExc_TypeError,
"%.500s() takes an at most %zd-sequence (%zd-sequence given)",
type->tp_name, max_len, len);
Py_DECREF(arg);
return NULL;
}
}
else {
if (len != min_len) {
PyErr_Format(PyExc_TypeError,
"%.500s() takes a %zd-sequence (%zd-sequence given)",
type->tp_name, min_len, len);
Py_DECREF(arg);
return NULL;
}
}
res = (PyStructSequence*) PyStructSequence_New(type);
if (res == NULL) {
return NULL;
}
for (i = 0; i < len; ++i) {
PyObject *v = PySequence_Fast_GET_ITEM(arg, i);
Py_INCREF(v);
res->ob_item[i] = v;
}
for (; i < max_len; ++i) {
if (dict && (ob = PyDict_GetItemString(
dict, type->tp_members[i-n_unnamed_fields].name))) {
}
else {
ob = Py_None;
}
Py_INCREF(ob);
res->ob_item[i] = ob;
}
Py_DECREF(arg);
return (PyObject*) res;
}
示例8: parseLabel
static int parseLabel(PyObject *labels, PyObject *mapping, char *line,
int length) {
/* Append label to *labels*, extract identifier, and index label
position in the list. Return 1 when successful, 0 on failure. */
int i, ch, slash = 0, dash = 0;//, ipipe = 0, pipes[4] = {0, 0, 0, 0};
for (i = 0; i < length; i++) {
ch = line[i];
if (ch < 32 && ch != 20)
break;
else if (ch == '/' && slash == 0 && dash == 0)
slash = i;
else if (ch == '-' && slash > 0 && dash == 0)
dash = i;
//else if (line[i] == '|' && ipipe < 4)
// pipes[ipipe++] = i;
}
PyObject *label, *index;
#if PY_MAJOR_VERSION >= 3
label = PyUnicode_FromStringAndSize(line, i);
index = PyLong_FromSsize_t(PyList_Size(labels));
#else
label = PyString_FromStringAndSize(line, i);
index = PyInt_FromSsize_t(PyList_Size(labels));
#endif
if (!label || !index || PyList_Append(labels, label) < 0) {
PyObject *none = Py_None;
PyList_Append(labels, none);
Py_DECREF(none);
Py_XDECREF(index);
Py_XDECREF(label);
return 0;
}
if (slash > 0 && dash > slash) {
Py_DECREF(label);
#if PY_MAJOR_VERSION >= 3
label = PyUnicode_FromStringAndSize(line, slash);
#else
label = PyString_FromStringAndSize(line, slash);
#endif
}
if (PyDict_Contains(mapping, label)) {
PyObject *item = PyDict_GetItem(mapping, label); /* borrowed */
if (PyList_Check(item)) {
PyList_Append(item, index);
Py_DECREF(index);
} else {
PyObject *list = PyList_New(2); /* new reference */
PyList_SetItem(list, 0, item);
Py_INCREF(item);
PyList_SetItem(list, 1, index); /* steals reference, no DECREF */
PyDict_SetItem(mapping, label, list);
Py_DECREF(list);
}
} else {
PyDict_SetItem(mapping, label, index);
Py_DECREF(index);
}
Py_DECREF(label);
return 1;
}
示例9: getCompiledCode
CompiledPythonFragment * getCompiledCode( Table * table, int pkey, const QString & pCode, const QString & codeName )
{
CompiledPythonFragment * ret = 0;
ensurePythonInitialized();
// Create the key for looking up the code fragment in the cache
QPair<Table*,int> codeKey = qMakePair(table,pkey);
// Return the cached code fragment, if the code still matches
if( codeCache.contains( codeKey ) ) {
CompiledPythonFragment * frag = &codeCache[codeKey];
// This should actually be very fast because of QString's
// implicit sharing, should usually just be a pointer comparison
if( frag->codeString == pCode )
return frag;
// Remove from cache if the fragment is out of date
// TODO: This should free any references and remove the module
// this isn't a big deal though, since code fragments won't
// change very often during program execution
codeCache.remove( codeKey );
}
if( pCode.isEmpty() )
return 0;
// Compile the code
CompiledPythonFragment frag;
frag.codeString = pCode;
SIP_BLOCK_THREADS
frag.code = (PyCodeObject*)Py_CompileString( pCode.toLatin1(), codeName.toLatin1(), Py_file_input );
SIP_UNBLOCK_THREADS
if( !frag.code )
{
PyErr_Print();
LOG_5( "PathTemplate:getCompiledCode: Error Compiling Python code for: " + table->schema()->tableName() + " " + QString::number( pkey ) + " " + codeName );
return 0;
}
// Load the code into a module
// This is the only way i could figure out how to make the globals work properly
// before i was using PyEval_EvalCode, passing the __main__ dict as the globals
// but this wasn't working properly when calling the functions later, because
// the import statements were lost.
// This method works great and takes less code.
// Generate a unique module name
QString moduleName = "__" + table->schema()->tableName() + "__" + QString::number(pkey) + "__";
// Returns a NEW ref
SIP_BLOCK_THREADS
PyObject * module = PyImport_ExecCodeModule(moduleName.toLatin1().data(),(PyObject*)frag.code);
if( !module ) {
PyErr_Print();
LOG_3( "Unable to execute code module" );
}
// Save the modules dict, so we can lookup the function later
else {
frag.locals = PyModule_GetDict(module);
Py_INCREF(frag.locals);
codeCache[codeKey] = frag;
ret = &codeCache[codeKey];
}
SIP_UNBLOCK_THREADS
return ret;
}
示例10: tok_stdin_decode
static int
tok_stdin_decode(struct tok_state *tok, char **inp)
{
PyObject *enc, *sysstdin, *decoded, *utf8;
const char *encoding;
char *converted;
if (PySys_GetFile((char *)"stdin", NULL) != stdin)
return 0;
sysstdin = PySys_GetObject("stdin");
if (sysstdin == NULL || !PyFile_Check(sysstdin))
return 0;
enc = ((PyFileObject *)sysstdin)->f_encoding;
if (enc == NULL || !PyString_Check(enc))
return 0;
Py_INCREF(enc);
encoding = PyString_AsString(enc);
decoded = PyUnicode_Decode(*inp, strlen(*inp), encoding, NULL);
if (decoded == NULL)
goto error_clear;
utf8 = PyUnicode_AsEncodedString(decoded, "utf-8", NULL);
Py_DECREF(decoded);
if (utf8 == NULL)
goto error_clear;
assert(PyString_Check(utf8));
converted = new_string(PyString_AS_STRING(utf8),
PyString_GET_SIZE(utf8));
Py_DECREF(utf8);
if (converted == NULL)
goto error_nomem;
PyMem_FREE(*inp);
*inp = converted;
if (tok->encoding != NULL)
PyMem_FREE(tok->encoding);
tok->encoding = new_string(encoding, strlen(encoding));
if (tok->encoding == NULL)
goto error_nomem;
Py_DECREF(enc);
return 0;
error_nomem:
Py_DECREF(enc);
tok->done = E_NOMEM;
return -1;
error_clear:
Py_DECREF(enc);
if (!PyErr_ExceptionMatches(PyExc_UnicodeDecodeError)) {
tok->done = E_ERROR;
return -1;
}
/* Fallback to iso-8859-1: for backward compatibility */
PyErr_Clear();
return 0;
}
示例11: complex_new
static PyObject *
complex_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
PyObject *r, *i, *tmp, *f;
PyNumberMethods *nbr, *nbi = NULL;
Py_complex cr, ci;
int own_r = 0;
int cr_is_complex = 0;
int ci_is_complex = 0;
static PyObject *complexstr;
static char *kwlist[] = {"real", "imag", 0};
r = Py_False;
i = NULL;
if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OO:complex", kwlist,
&r, &i))
return NULL;
/* Special-case for a single argument when type(arg) is complex. */
if (PyComplex_CheckExact(r) && i == NULL &&
type == &PyComplex_Type) {
/* Note that we can't know whether it's safe to return
a complex *subclass* instance as-is, hence the restriction
to exact complexes here. If either the input or the
output is a complex subclass, it will be handled below
as a non-orthogonal vector. */
Py_INCREF(r);
return r;
}
if (PyUnicode_Check(r)) {
if (i != NULL) {
PyErr_SetString(PyExc_TypeError,
"complex() can't take second arg"
" if first is a string");
return NULL;
}
return complex_subtype_from_string(type, r);
}
if (i != NULL && PyUnicode_Check(i)) {
PyErr_SetString(PyExc_TypeError,
"complex() second arg can't be a string");
return NULL;
}
/* XXX Hack to support classes with __complex__ method */
if (complexstr == NULL) {
complexstr = PyUnicode_InternFromString("__complex__");
if (complexstr == NULL)
return NULL;
}
f = PyObject_GetAttr(r, complexstr);
if (f == NULL)
PyErr_Clear();
else {
PyObject *args = PyTuple_New(0);
if (args == NULL)
return NULL;
r = PyEval_CallObject(f, args);
Py_DECREF(args);
Py_DECREF(f);
if (r == NULL)
return NULL;
own_r = 1;
}
nbr = r->ob_type->tp_as_number;
if (i != NULL)
nbi = i->ob_type->tp_as_number;
if (nbr == NULL || nbr->nb_float == NULL ||
((i != NULL) && (nbi == NULL || nbi->nb_float == NULL))) {
PyErr_SetString(PyExc_TypeError,
"complex() argument must be a string or a number");
if (own_r) {
Py_DECREF(r);
}
return NULL;
}
/* If we get this far, then the "real" and "imag" parts should
both be treated as numbers, and the constructor should return a
complex number equal to (real + imag*1j).
Note that we do NOT assume the input to already be in canonical
form; the "real" and "imag" parts might themselves be complex
numbers, which slightly complicates the code below. */
if (PyComplex_Check(r)) {
/* Note that if r is of a complex subtype, we're only
retaining its real & imag parts here, and the return
value is (properly) of the builtin complex type. */
cr = ((PyComplexObject*)r)->cval;
cr_is_complex = 1;
if (own_r) {
Py_DECREF(r);
}
}
else {
/* The "real" part really is entirely real, and contributes
nothing in the imaginary direction.
Just treat it as a double. */
tmp = PyNumber_Float(r);
if (own_r) {
//.........这里部分代码省略.........
示例12: gen_send_ex
static PyObject *
gen_send_ex(PyGenObject *gen, PyObject *arg, int exc)
{
PyThreadState *tstate = PyThreadState_GET();
PyFrameObject *f = gen->gi_frame;
PyObject *result;
if (gen->gi_running) {
PyErr_SetString(PyExc_ValueError,
"generator already executing");
return NULL;
}
if (f==NULL || f->f_stacktop == NULL) {
/* Only set exception if called from send() */
if (arg && !exc)
PyErr_SetNone(PyExc_StopIteration);
return NULL;
}
if (f->f_lasti == -1) {
if (arg && arg != Py_None) {
PyErr_SetString(PyExc_TypeError,
"can't send non-None value to a "
"just-started generator");
return NULL;
}
} else {
/* Push arg onto the frame's value stack */
result = arg ? arg : Py_None;
Py_INCREF(result);
*(f->f_stacktop++) = result;
}
/* Generators always return to their most recent caller, not
* necessarily their creator. */
Py_XINCREF(tstate->frame);
assert(f->f_back == NULL);
f->f_back = tstate->frame;
gen->gi_running = 1;
result = PyEval_EvalFrameEx(f, exc);
gen->gi_running = 0;
/* Don't keep the reference to f_back any longer than necessary. It
* may keep a chain of frames alive or it could create a reference
* cycle. */
assert(f->f_back == tstate->frame);
Py_CLEAR(f->f_back);
/* If the generator just returned (as opposed to yielding), signal
* that the generator is exhausted. */
if (result == Py_None && f->f_stacktop == NULL) {
Py_DECREF(result);
result = NULL;
/* Set exception if not called by gen_iternext() */
if (arg)
PyErr_SetNone(PyExc_StopIteration);
}
if (!result || f->f_stacktop == NULL) {
/* generator can't be rerun, so release the frame */
Py_DECREF(f);
gen->gi_frame = NULL;
}
return result;
}
示例13: gen_throw
static PyObject *
gen_throw(PyGenObject *gen, PyObject *args)
{
PyObject *typ;
PyObject *tb = NULL;
PyObject *val = NULL;
if (!PyArg_UnpackTuple(args, "throw", 1, 3, &typ, &val, &tb))
return NULL;
/* First, check the traceback argument, replacing None with
NULL. */
if (tb == Py_None)
tb = NULL;
else if (tb != NULL && !PyTraceBack_Check(tb)) {
PyErr_SetString(PyExc_TypeError,
"throw() third argument must be a traceback object");
return NULL;
}
Py_INCREF(typ);
Py_XINCREF(val);
Py_XINCREF(tb);
if (PyExceptionClass_Check(typ)) {
PyErr_NormalizeException(&typ, &val, &tb);
}
else if (PyExceptionInstance_Check(typ)) {
/* Raising an instance. The value should be a dummy. */
if (val && val != Py_None) {
PyErr_SetString(PyExc_TypeError,
"instance exception may not have a separate value");
goto failed_throw;
}
else {
/* Normalize to raise <class>, <instance> */
Py_XDECREF(val);
val = typ;
typ = PyExceptionInstance_Class(typ);
Py_INCREF(typ);
}
}
else {
/* Not something you can raise. throw() fails. */
PyErr_Format(PyExc_TypeError,
"exceptions must be classes, or instances, not %s",
typ->ob_type->tp_name);
goto failed_throw;
}
PyErr_Restore(typ, val, tb);
return gen_send_ex(gen, Py_None, 1);
failed_throw:
/* Didn't use our arguments, so restore their original refcounts */
Py_DECREF(typ);
Py_XDECREF(val);
Py_XDECREF(tb);
return NULL;
}
示例14: init_billiard
PyMODINIT_FUNC
init_billiard(void)
{
PyObject *module, *temp, *value;
/* Initialize module */
module = Py_InitModule("_billiard", Billiard_module_methods);
if (!module)
return;
/* Get copy of objects from pickle */
temp = PyImport_ImportModule(PICKLE_MODULE);
if (!temp)
return;
Billiard_pickle_dumps = PyObject_GetAttrString(temp, "dumps");
Billiard_pickle_loads = PyObject_GetAttrString(temp, "loads");
Billiard_pickle_protocol = PyObject_GetAttrString(temp, "HIGHEST_PROTOCOL");
Py_XDECREF(temp);
/* Get copy of BufferTooShort */
temp = PyImport_ImportModule("billiard");
if (!temp)
return;
Billiard_BufferTooShort = PyObject_GetAttrString(temp, "BufferTooShort");
Py_XDECREF(temp);
/* Add connection type to module */
if (PyType_Ready(&BilliardConnectionType) < 0)
return;
Py_INCREF(&BilliardConnectionType);
PyModule_AddObject(module, "Connection", (PyObject*)&BilliardConnectionType);
#if defined(MS_WINDOWS) || \
(defined(HAVE_SEM_OPEN) && !defined(POSIX_SEMAPHORES_NOT_ENABLED))
/* Add SemLock type to module */
if (PyType_Ready(&BilliardSemLockType) < 0)
return;
Py_INCREF(&BilliardSemLockType);
PyDict_SetItemString(BilliardSemLockType.tp_dict, "SEM_VALUE_MAX",
Py_BuildValue("i", SEM_VALUE_MAX));
PyModule_AddObject(module, "SemLock", (PyObject*)&BilliardSemLockType);
#endif
#ifdef MS_WINDOWS
/* Add PipeConnection to module */
if (PyType_Ready(&BilliardPipeConnectionType) < 0)
return;
Py_INCREF(&BilliardPipeConnectionType);
PyModule_AddObject(module, "PipeConnection",
(PyObject*)&BilliardPipeConnectionType);
/* Initialize win32 class and add to multiprocessing */
temp = create_win32_namespace();
if (!temp)
return;
PyModule_AddObject(module, "win32", temp);
/* Initialize the event handle used to signal Ctrl-C */
sigint_event = CreateEvent(NULL, TRUE, FALSE, NULL);
if (!sigint_event) {
PyErr_SetFromWindowsErr(0);
return;
}
if (!SetConsoleCtrlHandler(ProcessingCtrlHandler, TRUE)) {
PyErr_SetFromWindowsErr(0);
return;
}
#endif
/* Add configuration macros */
temp = PyDict_New();
if (!temp)
return;
#define ADD_FLAG(name) \
value = Py_BuildValue("i", name); \
if (value == NULL) { Py_DECREF(temp); return; } \
if (PyDict_SetItemString(temp, #name, value) < 0) { \
Py_DECREF(temp); Py_DECREF(value); return; } \
Py_DECREF(value)
#if defined(HAVE_SEM_OPEN) && !defined(POSIX_SEMAPHORES_NOT_ENABLED)
ADD_FLAG(HAVE_SEM_OPEN);
#endif
#ifdef HAVE_SEM_TIMEDWAIT
ADD_FLAG(HAVE_SEM_TIMEDWAIT);
#endif
#ifdef HAVE_FD_TRANSFER
ADD_FLAG(HAVE_FD_TRANSFER);
#endif
#ifdef HAVE_BROKEN_SEM_GETVALUE
ADD_FLAG(HAVE_BROKEN_SEM_GETVALUE);
#endif
#ifdef HAVE_BROKEN_SEM_UNLINK
ADD_FLAG(HAVE_BROKEN_SEM_UNLINK);
#endif
if (PyModule_AddObject(module, "flags", temp) < 0)
return;
}
示例15: tuplerichcompare
static PyObject* tuplerichcompare(PyObject* v, PyObject* w, int op) noexcept {
BoxedTuple* vt, *wt;
Py_ssize_t i;
Py_ssize_t vlen, wlen;
if (!PyTuple_Check(v) || !PyTuple_Check(w)) {
Py_INCREF(Py_NotImplemented);
return Py_NotImplemented;
}
vt = (BoxedTuple*)v;
wt = (BoxedTuple*)w;
vlen = Py_SIZE(vt);
wlen = Py_SIZE(wt);
/* Note: the corresponding code for lists has an "early out" test
* here when op is EQ or NE and the lengths differ. That pays there,
* but Tim was unable to find any real code where EQ/NE tuple
* compares don't have the same length, so testing for it here would
* have cost without benefit.
*/
/* Search for the first index where items are different.
* Note that because tuples are immutable, it's safe to reuse
* vlen and wlen across the comparison calls.
*/
for (i = 0; i < vlen && i < wlen; i++) {
int k = PyObject_RichCompareBool(vt->elts[i], wt->elts[i], Py_EQ);
if (k < 0)
return NULL;
if (!k)
break;
}
if (i >= vlen || i >= wlen) {
/* No more items to compare -- compare sizes */
int cmp;
PyObject* res;
switch (op) {
case Py_LT:
cmp = vlen < wlen;
break;
case Py_LE:
cmp = vlen <= wlen;
break;
case Py_EQ:
cmp = vlen == wlen;
break;
case Py_NE:
cmp = vlen != wlen;
break;
case Py_GT:
cmp = vlen > wlen;
break;
case Py_GE:
cmp = vlen >= wlen;
break;
default:
return NULL; /* cannot happen */
}
if (cmp)
res = Py_True;
else
res = Py_False;
Py_INCREF(res);
return res;
}
/* We have an item that differs -- shortcuts for EQ/NE */
if (op == Py_EQ) {
Py_INCREF(Py_False);
return Py_False;
}
if (op == Py_NE) {
Py_INCREF(Py_True);
return Py_True;
}
/* Compare the final item again using the proper operator */
return PyObject_RichCompare(vt->elts[i], wt->elts[i], op);
}