本文整理汇总了C++中PyTuple_SET_ITEM函数的典型用法代码示例。如果您正苦于以下问题:C++ PyTuple_SET_ITEM函数的具体用法?C++ PyTuple_SET_ITEM怎么用?C++ PyTuple_SET_ITEM使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了PyTuple_SET_ITEM函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: PyTuple_FromTupleDescAndParameters
//.........这里部分代码省略.........
PyErr_Format(PyExc_TypeError,
"requires exactly %d arguments, given %d",
td->natts, (args_len + kw_len));
return(NULL);
}
rob = PyTuple_New(td->natts);
/*
* There are a few ways this could be implemented,
* but it seems the most reasonable is to first set
* any available keywords and fill in the gaps with
* the positional args.
*/
if (kw_len > 0)
{
PyObj ob_key, kw_iter;
kw_iter = PyObject_GetIter(kw);
if (kw_iter == NULL)
{
Py_DECREF(rob);
return(NULL);
}
while ((ob_key = PyIter_Next(kw_iter)) != NULL)
{
PyObj ob, ob_str;
char *obstr;
int i;
ob_str = ob_key;
Py_INCREF(ob_str);
PyObject_StrBytes(&ob_str);
if (ob_str == NULL)
{
Py_DECREF(kw_iter);
Py_DECREF(rob);
return(NULL);
}
obstr = PyBytes_AS_STRING(ob_str);
/*
* Scan TupleDesc for attribute number. O(NM) :(
*/
for (i = 0; i < td->natts; ++i)
{
if (!strcmp(NameStr(td->attrs[i]->attname), obstr))
break;
}
Py_DECREF(ob_str);
/*
* No such attribute.
*/
if (i == td->natts)
{
PyObj invalid_kw_param;
Py_DECREF(rob);
Py_DECREF(kw_iter);
invalid_kw_param = PyUnicode_FromFormat(
"invalid keyword parameter %R", ob_key);
if (invalid_kw_param != NULL)
{
PyErr_SetObject(PyExc_TypeError, invalid_kw_param);
Py_DECREF(invalid_kw_param);
}
Py_DECREF(ob_key);
return(NULL);
}
ob = PyObject_GetItem(kw, ob_key);
Py_DECREF(ob_key);
PyTuple_SET_ITEM(rob, i, ob);
}
}
if (args_len > 0)
{
int i, ai;
for (i = 0, ai = 0; i < td->natts && ai < args_len; ++i)
{
PyObj ob;
if (PyTuple_GET_ITEM(rob, i) != NULL)
continue;
ob = PySequence_GetItem(args, ai);
if (ob == NULL)
{
Py_DECREF(rob);
return(NULL);
}
PyTuple_SET_ITEM(rob, i, ob);
++ai;
}
}
return(rob);
}
示例2: _CallPythonObject
/******************************************************************************
*
* Call the python object with all arguments
*
*/
static void _CallPythonObject(void *mem,
ffi_type *restype,
SETFUNC setfunc,
PyObject *callable,
PyObject *converters,
int flags,
void **pArgs)
{
Py_ssize_t i;
PyObject *result;
PyObject *arglist = NULL;
Py_ssize_t nArgs;
PyObject *error_object = NULL;
int *space;
#ifdef WITH_THREAD
PyGILState_STATE state = PyGILState_Ensure();
#endif
nArgs = PySequence_Length(converters);
/* Hm. What to return in case of error?
For COM, 0xFFFFFFFF seems better than 0.
*/
if (nArgs < 0) {
PrintError("BUG: PySequence_Length");
goto Done;
}
arglist = PyTuple_New(nArgs);
if (!arglist) {
PrintError("PyTuple_New()");
goto Done;
}
for (i = 0; i < nArgs; ++i) {
/* Note: new reference! */
PyObject *cnv = PySequence_GetItem(converters, i);
StgDictObject *dict;
if (cnv)
dict = PyType_stgdict(cnv);
else {
PrintError("Getting argument converter %d\n", i);
goto Done;
}
if (dict && dict->getfunc && !_ctypes_simple_instance(cnv)) {
PyObject *v = dict->getfunc(*pArgs, dict->size);
if (!v) {
PrintError("create argument %d:\n", i);
Py_DECREF(cnv);
goto Done;
}
PyTuple_SET_ITEM(arglist, i, v);
/* XXX XXX XX
We have the problem that c_byte or c_short have dict->size of
1 resp. 4, but these parameters are pushed as sizeof(int) bytes.
BTW, the same problem occurs when they are pushed as parameters
*/
} else if (dict) {
/* Hm, shouldn't we use PyCData_AtAddress() or something like that instead? */
CDataObject *obj = (CDataObject *)PyObject_CallFunctionObjArgs(cnv, NULL);
if (!obj) {
PrintError("create argument %d:\n", i);
Py_DECREF(cnv);
goto Done;
}
if (!CDataObject_Check(obj)) {
Py_DECREF(obj);
Py_DECREF(cnv);
PrintError("unexpected result of create argument %d:\n", i);
goto Done;
}
memcpy(obj->b_ptr, *pArgs, dict->size);
PyTuple_SET_ITEM(arglist, i, (PyObject *)obj);
#ifdef MS_WIN32
TryAddRef(dict, obj);
#endif
} else {
PyErr_SetString(PyExc_TypeError,
"cannot build parameter");
PrintError("Parsing argument %d\n", i);
Py_DECREF(cnv);
goto Done;
}
Py_DECREF(cnv);
/* XXX error handling! */
pArgs++;
}
#define CHECK(what, x) \
if (x == NULL) _ctypes_add_traceback(what, "_ctypes/callbacks.c", __LINE__ - 1), PyErr_Print()
if (flags & (FUNCFLAG_USE_ERRNO | FUNCFLAG_USE_LASTERROR)) {
error_object = _ctypes_get_errobj(&space);
if (error_object == NULL)
goto Done;
if (flags & FUNCFLAG_USE_ERRNO) {
//.........这里部分代码省略.........
示例3: PyTuple_Size
//.........这里部分代码省略.........
}
}
else
{
if(PyArg_ParseTuple(args, "O|O", &pathobj, &path_argsobj) == -1)
{
PyErr_Format(PyExc_TypeError, "KBEngine::listPathRes(): args[path, pathargs=\'*.*\'] is error!");
PyErr_PrintEx(0);
return 0;
}
if(PyUnicode_Check(path_argsobj))
{
wchar_t* fargs = NULL;
fargs = PyUnicode_AsWideCharString(path_argsobj, NULL);
wExtendName = fargs;
PyMem_Free(fargs);
}
else
{
if(PySequence_Check(path_argsobj))
{
wExtendName = L"";
Py_ssize_t size = PySequence_Size(path_argsobj);
for(int i=0; i<size; i++)
{
PyObject* pyobj = PySequence_GetItem(path_argsobj, i);
if(!PyUnicode_Check(pyobj))
{
PyErr_Format(PyExc_TypeError, "KBEngine::listPathRes(): args[path, pathargs=\'*.*\'] is error!");
PyErr_PrintEx(0);
return 0;
}
wchar_t* wtemp = NULL;
wtemp = PyUnicode_AsWideCharString(pyobj, NULL);
wExtendName += wtemp;
wExtendName += L"|";
PyMem_Free(wtemp);
}
}
else
{
PyErr_Format(PyExc_TypeError, "KBEngine::listPathRes(): args[pathargs] is error!");
PyErr_PrintEx(0);
return 0;
}
}
}
if(!PyUnicode_Check(pathobj))
{
PyErr_Format(PyExc_TypeError, "KBEngine::listPathRes(): args[path] is error!");
PyErr_PrintEx(0);
return 0;
}
if(wExtendName.size() == 0)
{
PyErr_Format(PyExc_TypeError, "KBEngine::listPathRes(): args[pathargs] is NULL!");
PyErr_PrintEx(0);
return 0;
}
if(wExtendName[0] == '.')
wExtendName.erase(wExtendName.begin());
if(wExtendName.size() == 0)
wExtendName = L"*";
wchar_t* respath = PyUnicode_AsWideCharString(pathobj, NULL);
if(respath == NULL)
{
PyErr_Format(PyExc_TypeError, "KBEngine::listPathRes(): args[path] is NULL!");
PyErr_PrintEx(0);
return 0;
}
char* cpath = strutil::wchar2char(respath);
std::string foundPath = Resmgr::getSingleton().matchPath(cpath);
free(cpath);
PyMem_Free(respath);
respath = strutil::char2wchar(foundPath.c_str());
std::vector<std::wstring> results;
Resmgr::getSingleton().listPathRes(respath, wExtendName, results);
PyObject* pyresults = PyTuple_New(results.size());
std::vector<std::wstring>::iterator iter = results.begin();
int i = 0;
for(; iter != results.end(); iter++)
{
PyTuple_SET_ITEM(pyresults, i++, PyUnicode_FromWideChar((*iter).c_str(), (*iter).size()));
}
free(respath);
return pyresults;
}
示例4: extra_arguments
static
PyObject *call_python_function(PyObject *func, npy_intp n, double *x,
PyObject *args, PyObject *error_obj)
{
/*
This is a generic function to call a python function that takes a 1-D
sequence as a first argument and optional extra_arguments (should be a
zero-length tuple if none desired). The result of the function is
returned in a multiarray object.
-- build sequence object from values in x.
-- add extra arguments (if any) to an argument list.
-- call Python callable object
-- check if error occurred:
if so return NULL
-- if no error, place result of Python code into multiarray object.
*/
PyArrayObject *sequence = NULL;
PyObject *arglist = NULL;
PyObject *arg1 = NULL;
PyObject *result = NULL;
PyArrayObject *result_array = NULL;
/* Build sequence argument from inputs */
sequence = (PyArrayObject *) PyArray_SimpleNewFromData(1, &n, NPY_DOUBLE,
(char *) x);
if (sequence == NULL) {
goto fail;
}
/* Build argument list */
if ((arg1 = PyTuple_New(1)) == NULL) {
Py_DECREF(sequence);
return NULL;
}
PyTuple_SET_ITEM(arg1, 0, (PyObject *)sequence);
/* arg1 now owns sequence reference */
if ((arglist = PySequence_Concat(arg1, args)) == NULL) {
goto fail;
}
Py_DECREF(arg1); /* arglist has a reference to sequence, now. */
arg1 = NULL;
/*
* Call function object --- variable passed to routine. Extra
* arguments are in another passed variable.
*/
if ((result = PyEval_CallObject(func, arglist))==NULL) {
goto fail;
}
result_array = (PyArrayObject *) PyArray_ContiguousFromObject(result,
NPY_DOUBLE, 0, 0);
if (result_array == NULL) {
goto fail;
}
Py_DECREF(result);
Py_DECREF(arglist);
return (PyObject *) result_array;
fail:
Py_XDECREF(arglist);
Py_XDECREF(result);
Py_XDECREF(arg1);
return NULL;
}
示例5: _py_args_combine_and_check_length
/**
* _py_args_combine_and_check_length:
* @cache: PyGICallableCache
* @py_args: the tuple of positional arguments.
* @py_kwargs: the dict of keyword arguments to be merged with py_args.
*
* Returns: New value reference to the combined py_args and py_kwargs.
*/
static PyObject *
_py_args_combine_and_check_length (PyGICallableCache *cache,
PyObject *py_args,
PyObject *py_kwargs)
{
PyObject *combined_py_args = NULL;
Py_ssize_t n_py_args, n_py_kwargs, i;
guint n_expected_args = cache->n_py_args;
GSList *l;
n_py_args = PyTuple_GET_SIZE (py_args);
if (py_kwargs == NULL)
n_py_kwargs = 0;
else
n_py_kwargs = PyDict_Size (py_kwargs);
/* Fast path, we already have the exact number of args and not kwargs. */
if (n_py_kwargs == 0 && n_py_args == n_expected_args && cache->user_data_varargs_index < 0) {
Py_INCREF (py_args);
return py_args;
}
if (cache->user_data_varargs_index < 0 && n_expected_args < n_py_args) {
char *full_name = pygi_callable_cache_get_full_name (cache);
PyErr_Format (PyExc_TypeError,
"%.200s() takes exactly %d %sargument%s (%zd given)",
full_name,
n_expected_args,
n_py_kwargs > 0 ? "non-keyword " : "",
n_expected_args == 1 ? "" : "s",
n_py_args);
g_free (full_name);
return NULL;
}
if (cache->user_data_varargs_index >= 0 && n_py_kwargs > 0 && n_expected_args < n_py_args) {
char *full_name = pygi_callable_cache_get_full_name (cache);
PyErr_Format (PyExc_TypeError,
"%.200s() cannot use variable user data arguments with keyword arguments",
full_name);
g_free (full_name);
return NULL;
}
if (n_py_kwargs > 0 && !_check_for_unexpected_kwargs (cache,
cache->arg_name_hash,
py_kwargs)) {
return NULL;
}
/* will hold arguments from both py_args and py_kwargs
* when they are combined into a single tuple */
combined_py_args = PyTuple_New (n_expected_args);
for (i = 0, l = cache->arg_name_list; i < n_expected_args && l; i++, l = l->next) {
PyObject *py_arg_item = NULL;
PyObject *kw_arg_item = NULL;
const gchar *arg_name = l->data;
int arg_cache_index = -1;
gboolean is_varargs_user_data = FALSE;
if (arg_name != NULL)
arg_cache_index = GPOINTER_TO_INT (g_hash_table_lookup (cache->arg_name_hash, arg_name));
is_varargs_user_data = cache->user_data_varargs_index >= 0 &&
arg_cache_index == cache->user_data_varargs_index;
if (n_py_kwargs > 0 && arg_name != NULL) {
/* NULL means this argument has no keyword name */
/* ex. the first argument to a method or constructor */
kw_arg_item = PyDict_GetItemString (py_kwargs, arg_name);
}
/* use a bounded retrieval of the original input */
if (i < n_py_args)
py_arg_item = PyTuple_GET_ITEM (py_args, i);
if (kw_arg_item == NULL && py_arg_item != NULL) {
if (is_varargs_user_data) {
/* For tail end user_data varargs, pull a slice off and we are done. */
PyObject *user_data = PyTuple_GetSlice (py_args, i, PY_SSIZE_T_MAX);
PyTuple_SET_ITEM (combined_py_args, i, user_data);
return combined_py_args;
} else {
Py_INCREF (py_arg_item);
PyTuple_SET_ITEM (combined_py_args, i, py_arg_item);
}
} else if (kw_arg_item != NULL && py_arg_item == NULL) {
if (is_varargs_user_data) {
/* Special case where user_data is passed as a keyword argument (user_data=foo)
* Wrap the value in a tuple to represent variable args for marshaling later on.
*/
//.........这里部分代码省略.........
示例6: subprocess_fork_exec
static PyObject *
subprocess_fork_exec(PyObject* self, PyObject *args)
{
PyObject *gc_module = NULL;
PyObject *executable_list, *py_fds_to_keep;
PyObject *env_list, *preexec_fn;
PyObject *process_args, *converted_args = NULL, *fast_args = NULL;
PyObject *preexec_fn_args_tuple = NULL;
int p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite;
int errpipe_read, errpipe_write, close_fds, restore_signals;
int call_setsid;
PyObject *cwd_obj, *cwd_obj2;
const char *cwd;
pid_t pid;
int need_to_reenable_gc = 0;
char *const *exec_array, *const *argv = NULL, *const *envp = NULL;
Py_ssize_t arg_num;
int import_lock_held = 0;
if (!PyArg_ParseTuple(
args, "OOpOOOiiiiiiiiiiO:fork_exec",
&process_args, &executable_list, &close_fds, &py_fds_to_keep,
&cwd_obj, &env_list,
&p2cread, &p2cwrite, &c2pread, &c2pwrite,
&errread, &errwrite, &errpipe_read, &errpipe_write,
&restore_signals, &call_setsid, &preexec_fn))
return NULL;
if (close_fds && errpipe_write < 3) { /* precondition */
PyErr_SetString(PyExc_ValueError, "errpipe_write must be >= 3");
return NULL;
}
if (PySequence_Length(py_fds_to_keep) < 0) {
PyErr_SetString(PyExc_ValueError, "cannot get length of fds_to_keep");
return NULL;
}
if (_sanity_check_python_fd_sequence(py_fds_to_keep)) {
PyErr_SetString(PyExc_ValueError, "bad value(s) in fds_to_keep");
return NULL;
}
/* We need to call gc.disable() when we'll be calling preexec_fn */
if (preexec_fn != Py_None) {
PyObject *result;
_Py_IDENTIFIER(isenabled);
_Py_IDENTIFIER(disable);
gc_module = PyImport_ImportModule("gc");
if (gc_module == NULL)
return NULL;
result = _PyObject_CallMethodId(gc_module, &PyId_isenabled, NULL);
if (result == NULL) {
Py_DECREF(gc_module);
return NULL;
}
need_to_reenable_gc = PyObject_IsTrue(result);
Py_DECREF(result);
if (need_to_reenable_gc == -1) {
Py_DECREF(gc_module);
return NULL;
}
result = _PyObject_CallMethodId(gc_module, &PyId_disable, NULL);
if (result == NULL) {
Py_DECREF(gc_module);
return NULL;
}
Py_DECREF(result);
}
exec_array = _PySequence_BytesToCharpArray(executable_list);
if (!exec_array)
goto cleanup;
/* Convert args and env into appropriate arguments for exec() */
/* These conversions are done in the parent process to avoid allocating
or freeing memory in the child process. */
if (process_args != Py_None) {
Py_ssize_t num_args;
/* Equivalent to: */
/* tuple(PyUnicode_FSConverter(arg) for arg in process_args) */
fast_args = PySequence_Fast(process_args, "argv must be a tuple");
if (fast_args == NULL)
goto cleanup;
num_args = PySequence_Fast_GET_SIZE(fast_args);
converted_args = PyTuple_New(num_args);
if (converted_args == NULL)
goto cleanup;
for (arg_num = 0; arg_num < num_args; ++arg_num) {
PyObject *borrowed_arg, *converted_arg;
borrowed_arg = PySequence_Fast_GET_ITEM(fast_args, arg_num);
if (PyUnicode_FSConverter(borrowed_arg, &converted_arg) == 0)
goto cleanup;
PyTuple_SET_ITEM(converted_args, arg_num, converted_arg);
}
argv = _PySequence_BytesToCharpArray(converted_args);
Py_CLEAR(converted_args);
Py_CLEAR(fast_args);
if (!argv)
goto cleanup;
//.........这里部分代码省略.........
示例7: ode_function
void
ode_function(int *n, double *t, double *y, double *ydot)
{
/*
This is the function called from the Fortran code it should
-- use call_python_function to get a multiarrayobject result
-- check for errors and set *n to -1 if any
-- otherwise place result of calculation in ydot
*/
PyArrayObject *result_array = NULL;
PyObject *arg1, *arglist;
/* Append t to argument list */
if ((arg1 = PyTuple_New(1)) == NULL) {
*n = -1;
return;
}
PyTuple_SET_ITEM(arg1, 0, PyFloat_FromDouble(*t));
/* arg1 now owns newly created reference */
if ((arglist = PySequence_Concat(arg1, global_params.extra_arguments)) == NULL) {
*n = -1;
Py_DECREF(arg1);
return;
}
Py_DECREF(arg1); /* arglist has reference */
result_array = (PyArrayObject *)call_python_function(global_params.python_function,
*n, y, arglist, odepack_error);
if (result_array == NULL) {
*n = -1;
Py_DECREF(arglist);
return;
}
if (PyArray_NDIM(result_array) > 1) {
*n = -1;
PyErr_Format(PyExc_RuntimeError,
"The array return by func must be one-dimensional, but got ndim=%d.",
PyArray_NDIM(result_array));
Py_DECREF(arglist);
Py_DECREF(result_array);
return;
}
if (PyArray_Size((PyObject *)result_array) != *n) {
PyErr_Format(PyExc_RuntimeError,
"The size of the array returned by func (%ld) does not match "
"the size of y0 (%d).",
PyArray_Size((PyObject *)result_array), *n);
*n = -1;
Py_DECREF(arglist);
Py_DECREF(result_array);
return;
}
memcpy(ydot, PyArray_DATA(result_array), (*n)*sizeof(double));
Py_DECREF(result_array);
Py_DECREF(arglist);
return;
}
示例8: PyTuple_GET_SIZE
static PyObject *next(PyObject *self)
{
ligolw_RowDumper *rowdumper = (ligolw_RowDumper *) self;
const Py_ssize_t n = PyTuple_GET_SIZE(rowdumper->attributes);
PyObject *tokens;
PyObject *row;
PyObject *result;
Py_ssize_t i;
/*
* retrieve the next row object
*/
if(!PyIter_Check(rowdumper->iter)) {
PyErr_SetObject(PyExc_TypeError, rowdumper->iter);
return NULL;
}
row = PyIter_Next(rowdumper->iter);
if(!row) {
if(!PyErr_Occurred()) {
Py_DECREF(rowdumper->iter);
rowdumper->iter = Py_None;
Py_INCREF(rowdumper->iter);
PyErr_SetNone(PyExc_StopIteration);
}
return NULL;
}
/*
* wipe out the tuple of tokens from the previous row, and start a
* new tuple
*/
Py_DECREF(rowdumper->tokens);
rowdumper->tokens = Py_None;
Py_INCREF(rowdumper->tokens);
tokens = PyTuple_New(n);
if(!tokens) {
Py_DECREF(row);
return NULL;
}
/*
* retrieve attributes from the row object one-by-one, convert to
* strings, and insert into new token tuple
*/
for(i = 0; i < n; i++) {
PyObject *val = PyObject_GetAttr(row, PyTuple_GET_ITEM(rowdumper->attributes, i));
PyObject *token;
if(!val) {
Py_DECREF(tokens);
Py_DECREF(row);
return NULL;
}
if(val == Py_None)
token = PyUnicode_FromUnicode(NULL, 0); /* u"" */
else
token = PyObject_CallFunctionObjArgs(PyTuple_GET_ITEM(rowdumper->formats, i), val, NULL);
Py_DECREF(val);
if(!token) {
Py_DECREF(tokens);
Py_DECREF(row);
return NULL;
}
PyTuple_SET_ITEM(tokens, i, token);
}
Py_DECREF(row);
/*
* that worked, so expose the new token tuple
*/
Py_DECREF(rowdumper->tokens);
rowdumper->tokens = tokens;
/*
* return tokens concatenated into a single string using the
* delimiter
*/
result = PyUnicode_Join(rowdumper->delimiter, rowdumper->tokens);
rowdumper->rows_converted += result != NULL;
return result;
}
示例9: PyObject_ClearWeakRefs
/* This function is called by the tp_dealloc handler to clear weak references.
*
* This iterates through the weak references for 'object' and calls callbacks
* for those references which have one. It returns when all callbacks have
* been attempted.
*/
void
PyObject_ClearWeakRefs(PyObject *object)
{
PyWeakReference **list;
if (object == NULL
|| !PyType_SUPPORTS_WEAKREFS(Py_TYPE(object))
|| object->ob_refcnt != 0) {
PyErr_BadInternalCall();
return;
}
list = GET_WEAKREFS_LISTPTR(object);
/* Remove the callback-less basic and proxy references */
if (*list != NULL && (*list)->wr_callback == NULL) {
clear_weakref(*list);
if (*list != NULL && (*list)->wr_callback == NULL)
clear_weakref(*list);
}
if (*list != NULL) {
PyWeakReference *current = *list;
Py_ssize_t count = _PyWeakref_GetWeakrefCount(current);
int restore_error = PyErr_Occurred() ? 1 : 0;
PyObject *err_type, *err_value, *err_tb;
if (restore_error)
PyErr_Fetch(&err_type, &err_value, &err_tb);
if (count == 1) {
PyObject *callback = current->wr_callback;
current->wr_callback = NULL;
clear_weakref(current);
if (callback != NULL) {
if (((PyObject *)current)->ob_refcnt > 0)
handle_callback(current, callback);
Py_DECREF(callback);
}
}
else {
PyObject *tuple;
Py_ssize_t i = 0;
tuple = PyTuple_New(count * 2);
if (tuple == NULL) {
if (restore_error)
PyErr_Fetch(&err_type, &err_value, &err_tb);
return;
}
for (i = 0; i < count; ++i) {
PyWeakReference *next = current->wr_next;
if (((PyObject *)current)->ob_refcnt > 0)
{
Py_INCREF(current);
PyTuple_SET_ITEM(tuple, i * 2, (PyObject *) current);
PyTuple_SET_ITEM(tuple, i * 2 + 1, current->wr_callback);
}
else {
Py_DECREF(current->wr_callback);
}
current->wr_callback = NULL;
clear_weakref(current);
current = next;
}
for (i = 0; i < count; ++i) {
PyObject *callback = PyTuple_GET_ITEM(tuple, i * 2 + 1);
/* The tuple may have slots left to NULL */
if (callback != NULL) {
PyObject *item = PyTuple_GET_ITEM(tuple, i * 2);
handle_callback((PyWeakReference *)item, callback);
}
}
Py_DECREF(tuple);
}
if (restore_error)
PyErr_Restore(err_type, err_value, err_tb);
}
}
示例10: rpmfi_iternext
/*@[email protected]*/
static PyObject *
rpmfi_iternext(rpmfiObject * s)
/*@globals _Py_NoneStruct @*/
/*@modifies s, _Py_NoneStruct @*/
{
PyObject * result = NULL;
/* Reset loop indices on 1st entry. */
if (!s->active) {
s->fi = rpmfiInit(s->fi, 0);
s->active = 1;
}
/* If more to do, return the file tuple. */
if (rpmfiNext(s->fi) >= 0) {
const char * FN = rpmfiFN(s->fi);
int FSize = rpmfiFSize(s->fi);
int FMode = rpmfiFMode(s->fi);
int FMtime = rpmfiFMtime(s->fi);
int FFlags = rpmfiFFlags(s->fi);
int FRdev = rpmfiFRdev(s->fi);
int FInode = rpmfiFInode(s->fi);
int FNlink = rpmfiFNlink(s->fi);
int FState = rpmfiFState(s->fi);
int VFlags = rpmfiVFlags(s->fi);
const char * FUser = rpmfiFUser(s->fi);
const char * FGroup = rpmfiFGroup(s->fi);
result = PyTuple_New(13);
if (FN == NULL) {
Py_INCREF(Py_None);
PyTuple_SET_ITEM(result, 0, Py_None);
} else
PyTuple_SET_ITEM(result, 0, Py_BuildValue("s", FN));
PyTuple_SET_ITEM(result, 1, PyInt_FromLong(FSize));
PyTuple_SET_ITEM(result, 2, PyInt_FromLong(FMode));
PyTuple_SET_ITEM(result, 3, PyInt_FromLong(FMtime));
PyTuple_SET_ITEM(result, 4, PyInt_FromLong(FFlags));
PyTuple_SET_ITEM(result, 5, PyInt_FromLong(FRdev));
PyTuple_SET_ITEM(result, 6, PyInt_FromLong(FInode));
PyTuple_SET_ITEM(result, 7, PyInt_FromLong(FNlink));
PyTuple_SET_ITEM(result, 8, PyInt_FromLong(FState));
PyTuple_SET_ITEM(result, 9, PyInt_FromLong(VFlags));
if (FUser == NULL) {
Py_INCREF(Py_None);
PyTuple_SET_ITEM(result, 10, Py_None);
} else
PyTuple_SET_ITEM(result, 10, Py_BuildValue("s", FUser));
if (FGroup == NULL) {
Py_INCREF(Py_None);
PyTuple_SET_ITEM(result, 11, Py_None);
} else
PyTuple_SET_ITEM(result, 11, Py_BuildValue("s", FGroup));
PyTuple_SET_ITEM(result, 12, rpmfi_Digest(s));
} else
s->active = 0;
return result;
}
示例11: PY_GETSET_GETTER_DECL
PY_GETSET_GETTER_DECL(TempVertex, weights) {
PyObject* list = PyTuple_New(3);
for (size_t i = 0; i < 3; ++i)
PyTuple_SET_ITEM(list, i, pyPlasma_convert(self->fThis->fWeights[i]));
return list;
}
示例12: __adapt__
/*
def __adapt__(self, obj):
"""Adapt an object to the reciever
"""
if self.providedBy(obj):
return obj
for hook in adapter_hooks:
adapter = hook(self, obj)
if adapter is not None:
return adapter
*/
static PyObject *
__adapt__(PyObject *self, PyObject *obj)
{
PyObject *decl, *args, *adapter;
int implements, i, l;
decl = providedBy(NULL, obj);
if (decl == NULL)
return NULL;
if (PyObject_TypeCheck(decl, &SpecType))
{
PyObject *implied;
implied = inst_attr(decl, str_implied);
if (implied == NULL)
{
Py_DECREF(decl);
return NULL;
}
implements = PyDict_GetItem(implied, self) != NULL;
Py_DECREF(decl);
}
else
{
/* decl is probably a security proxy. We have to go the long way
around.
*/
PyObject *r;
r = PyObject_CallFunctionObjArgs(decl, self, NULL);
Py_DECREF(decl);
if (r == NULL)
return NULL;
implements = PyObject_IsTrue(r);
Py_DECREF(r);
}
if (implements)
{
Py_INCREF(obj);
return obj;
}
l = PyList_GET_SIZE(adapter_hooks);
args = PyTuple_New(2);
if (args == NULL)
return NULL;
Py_INCREF(self);
PyTuple_SET_ITEM(args, 0, self);
Py_INCREF(obj);
PyTuple_SET_ITEM(args, 1, obj);
for (i = 0; i < l; i++)
{
adapter = PyObject_CallObject(PyList_GET_ITEM(adapter_hooks, i), args);
if (adapter == NULL || adapter != Py_None)
{
Py_DECREF(args);
return adapter;
}
Py_DECREF(adapter);
}
Py_DECREF(args);
Py_INCREF(Py_None);
return Py_None;
}
示例13: PyPreprocessor_scanHeaders
PyObject * PyPreprocessor_scanHeaders( PyPreprocessor * self, PyObject * args, PyObject * kwds )
{
static char * kwlist[] = { "pp_ctx", "filename", NULL };
PyObject * pObject = 0;
PyObject * filename = 0;
assert( self->pp );
if ( !PyArg_ParseTupleAndKeywords( args, kwds, "OO", kwlist, &pObject, &filename ) )
return NULL;
if ( !pObject || ( (PyTypeObject *)PyObject_Type( pObject ) != &PyPreprocessingContextType ) )
{
PyErr_SetString( PyExc_Exception, "Invalid preprocessing context parameter." );
return NULL;
}
PyPreprocessingContext const * ppContext( reinterpret_cast<PyPreprocessingContext *>( pObject ) );
if ( filename && !PyUnicode_Check( filename ) )
{
PyErr_SetString( PyExc_Exception, "Expected a string as 'filename' parameter." );
return NULL;
}
Headers headers;
HeaderList missing;
PyThreadState * _save;
bool result;
try
{
Py_UNBLOCK_THREADS
result = self->pp->scanHeaders( *ppContext->ppContext, PyUnicode_AsUTF8( filename ), headers, missing );
}
catch ( std::runtime_error const & error )
{
Py_BLOCK_THREADS
PyErr_SetString( PyExc_RuntimeError, error.what() );
return NULL;
}
catch ( std::exception const & error )
{
Py_BLOCK_THREADS
PyErr_SetString( PyExc_Exception, error.what() );
return NULL;
}
catch ( ... )
{
Py_BLOCK_THREADS
PyErr_SetString( PyExc_Exception, "Unhandled exception" );
return NULL;
}
if ( !result )
{
Py_BLOCK_THREADS
PyErr_SetString( PyExc_Exception, "Failed to preprocess file." );
return NULL;
}
// Group result by dir.
typedef std::vector<Header const *> HeaderPtrList;
typedef std::unordered_map<Dir, HeaderPtrList> DirsAndHeaders;
DirsAndHeaders dirsAndHeaders;
for ( Header const & header : headers )
dirsAndHeaders[ header.dir ].push_back( &header );
Py_BLOCK_THREADS
PyObject * dirsTuple = PyTuple_New( dirsAndHeaders.size() );
std::size_t dirIndex( 0 );
for ( DirsAndHeaders::value_type const & dirAndHeaders : dirsAndHeaders )
{
PyObject * headersInDirTuple = PyTuple_New( dirAndHeaders.second.size() );
std::size_t headersInDirTupleIndex( 0 );
for ( Header const * header : dirAndHeaders.second )
{
PyObject * headerEntry = PyTuple_New( 3 );
PyTuple_SET_ITEM( headerEntry, 0, PyUnicode_FromStringAndSize( header->name.get().data(), header->name.get().size() ) );
PyObject * const isRelative( header->relative ? Py_True : Py_False );
Py_INCREF( isRelative );
PyTuple_SET_ITEM( headerEntry, 1, isRelative );
PyContentEntry * contentEntry( (PyContentEntry *)_PyObject_New( &PyContentEntryType ) );
contentEntry->ptr = header->contentEntry.get();
intrusive_ptr_add_ref( contentEntry->ptr );
PyTuple_SET_ITEM( headerEntry, 2, (PyObject *)contentEntry );
PyTuple_SET_ITEM( headersInDirTuple, headersInDirTupleIndex++, headerEntry );
}
PyObject * dirTuple = PyTuple_New( 2 );
llvm::StringRef const dirStr( dirAndHeaders.first.get() );
PyObject * dir = PyUnicode_FromStringAndSize( dirStr.data(), dirStr.size() );
PyTuple_SET_ITEM( dirTuple, 0, dir );
PyTuple_SET_ITEM( dirTuple, 1, headersInDirTuple );
PyTuple_SET_ITEM( dirsTuple, dirIndex++, dirTuple );
}
PyObject * missingHeadersTuple = PyTuple_New( missing.size() );
//.........这里部分代码省略.........
示例14: do_python
static rlm_rcode_t do_python(rlm_python_t *inst, REQUEST *request, PyObject *pFunc, char const *funcname, bool worker)
{
vp_cursor_t cursor;
VALUE_PAIR *vp;
PyObject *pRet = NULL;
PyObject *pArgs = NULL;
int tuplelen;
int ret;
PyGILState_STATE gstate;
PyThreadState *prev_thread_state = NULL; /* -Wuninitialized */
memset(&gstate, 0, sizeof(gstate)); /* -Wuninitialized */
/* Return with "OK, continue" if the function is not defined. */
if (!pFunc)
return RLM_MODULE_NOOP;
#ifdef HAVE_PTHREAD_H
gstate = PyGILState_Ensure();
if (worker) {
PyThreadState *my_thread_state;
my_thread_state = fr_thread_local_init(local_thread_state, do_python_cleanup);
if (!my_thread_state) {
my_thread_state = PyThreadState_New(inst->main_thread_state->interp);
if (!my_thread_state) {
REDEBUG("Failed initialising local PyThreadState on first run");
PyGILState_Release(gstate);
return RLM_MODULE_FAIL;
}
ret = fr_thread_local_set(local_thread_state, my_thread_state);
if (ret != 0) {
REDEBUG("Failed storing PyThreadState in TLS: %s", fr_syserror(ret));
PyThreadState_Clear(my_thread_state);
PyThreadState_Delete(my_thread_state);
PyGILState_Release(gstate);
return RLM_MODULE_FAIL;
}
}
prev_thread_state = PyThreadState_Swap(my_thread_state); /* Swap in our local thread state */
}
#endif
/* Default return value is "OK, continue" */
ret = RLM_MODULE_OK;
/*
* We will pass a tuple containing (name, value) tuples
* We can safely use the Python function to build up a
* tuple, since the tuple is not used elsewhere.
*
* Determine the size of our tuple by walking through the packet.
* If request is NULL, pass None.
*/
tuplelen = 0;
if (request != NULL) {
for (vp = paircursor(&cursor, &request->packet->vps);
vp;
vp = pairnext(&cursor)) {
tuplelen++;
}
}
if (tuplelen == 0) {
Py_INCREF(Py_None);
pArgs = Py_None;
} else {
int i = 0;
if ((pArgs = PyTuple_New(tuplelen)) == NULL) {
ret = RLM_MODULE_FAIL;
goto finish;
}
for (vp = paircursor(&cursor, &request->packet->vps);
vp;
vp = pairnext(&cursor), i++) {
PyObject *pPair;
/* The inside tuple has two only: */
if ((pPair = PyTuple_New(2)) == NULL) {
ret = RLM_MODULE_FAIL;
goto finish;
}
if (mod_populate_vptuple(pPair, vp) == 0) {
/* Put the tuple inside the container */
PyTuple_SET_ITEM(pArgs, i, pPair);
} else {
Py_INCREF(Py_None);
PyTuple_SET_ITEM(pArgs, i, Py_None);
Py_DECREF(pPair);
}
}
}
/* Call Python function. */
pRet = PyObject_CallFunctionObjArgs(pFunc, pArgs, NULL);
if (!pRet) {
ret = RLM_MODULE_FAIL;
//.........这里部分代码省略.........
示例15: find_named_args
static int
find_named_args(DispatcherObject *self, PyObject **pargs, PyObject **pkws)
{
PyObject *oldargs = *pargs, *newargs;
PyObject *kws = *pkws;
Py_ssize_t pos_args = PyTuple_GET_SIZE(oldargs);
Py_ssize_t named_args, total_args, i;
Py_ssize_t func_args = PyTuple_GET_SIZE(self->argnames);
Py_ssize_t defaults = PyTuple_GET_SIZE(self->defargs);
/* Last parameter with a default value */
Py_ssize_t last_def = (self->has_stararg)
? func_args - 2
: func_args - 1;
/* First parameter with a default value */
Py_ssize_t first_def = last_def - defaults + 1;
/* Minimum number of required arguments */
Py_ssize_t minargs = first_def;
if (kws != NULL)
named_args = PyDict_Size(kws);
else
named_args = 0;
total_args = pos_args + named_args;
if (!self->has_stararg && total_args > func_args) {
PyErr_Format(PyExc_TypeError,
"too many arguments: expected %d, got %d",
(int) func_args, (int) total_args);
return -1;
}
else if (total_args < minargs) {
if (minargs == func_args)
PyErr_Format(PyExc_TypeError,
"not enough arguments: expected %d, got %d",
(int) minargs, (int) total_args);
else
PyErr_Format(PyExc_TypeError,
"not enough arguments: expected at least %d, got %d",
(int) minargs, (int) total_args);
return -1;
}
newargs = PyTuple_New(func_args);
if (!newargs)
return -1;
/* First pack the stararg */
if (self->has_stararg) {
Py_ssize_t stararg_size = Py_MAX(0, pos_args - func_args + 1);
PyObject *stararg = PyTuple_New(stararg_size);
if (!stararg) {
Py_DECREF(newargs);
return -1;
}
for (i = 0; i < stararg_size; i++) {
PyObject *value = PyTuple_GET_ITEM(oldargs, func_args - 1 + i);
Py_INCREF(value);
PyTuple_SET_ITEM(stararg, i, value);
}
/* Put it in last position */
PyTuple_SET_ITEM(newargs, func_args - 1, stararg);
}
for (i = 0; i < pos_args; i++) {
PyObject *value = PyTuple_GET_ITEM(oldargs, i);
if (self->has_stararg && i >= func_args - 1) {
/* Skip stararg */
break;
}
Py_INCREF(value);
PyTuple_SET_ITEM(newargs, i, value);
}
/* Iterate over missing positional arguments, try to find them in
named arguments or default values. */
for (i = pos_args; i < func_args; i++) {
PyObject *name = PyTuple_GET_ITEM(self->argnames, i);
if (self->has_stararg && i >= func_args - 1) {
/* Skip stararg */
break;
}
if (kws != NULL) {
/* Named argument? */
PyObject *value = PyDict_GetItem(kws, name);
if (value != NULL) {
Py_INCREF(value);
PyTuple_SET_ITEM(newargs, i, value);
named_args--;
continue;
}
}
if (i >= first_def && i <= last_def) {
/* Argument has a default value? */
PyObject *value = PyTuple_GET_ITEM(self->defargs, i - first_def);
Py_INCREF(value);
PyTuple_SET_ITEM(newargs, i, value);
continue;
}
else if (i < func_args - 1 || !self->has_stararg) {
PyErr_Format(PyExc_TypeError,
"missing argument '%s'",
PyString_AsString(name));
Py_DECREF(newargs);
//.........这里部分代码省略.........