本文整理汇总了C++中PyList_New函数的典型用法代码示例。如果您正苦于以下问题:C++ PyList_New函数的具体用法?C++ PyList_New怎么用?C++ PyList_New使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了PyList_New函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: memchr
void *uwsgi_request_subhandler_pump(struct wsgi_request *wsgi_req, struct uwsgi_app *wi) {
PyObject *zero;
int i;
PyObject *pydictkey, *pydictvalue;
char *port = memchr(wsgi_req->host, ':', wsgi_req->host_len);
if (port) {
zero = PyString_FromStringAndSize(wsgi_req->host, (port-wsgi_req->host));
PyDict_SetItemString(wsgi_req->async_environ, "server_name", zero);
Py_DECREF(zero);
zero = PyString_FromStringAndSize(port, wsgi_req->host_len-((port+1)-wsgi_req->host));
PyDict_SetItemString(wsgi_req->async_environ, "server_port", zero);
Py_DECREF(zero);
}
else {
zero = PyString_FromStringAndSize(wsgi_req->host, wsgi_req->host_len);
PyDict_SetItemString(wsgi_req->async_environ, "server_name", zero);
Py_DECREF(zero);
zero = PyString_FromStringAndSize("80", 2);
PyDict_SetItemString(wsgi_req->async_environ, "server_port", zero);
Py_DECREF(zero);
}
zero = PyString_FromStringAndSize(wsgi_req->remote_addr, wsgi_req->remote_addr_len);
PyDict_SetItemString(wsgi_req->async_environ, "remote_addr", zero);
Py_DECREF(zero);
zero = PyString_FromStringAndSize(wsgi_req->path_info, wsgi_req->path_info_len);
PyDict_SetItemString(wsgi_req->async_environ, "uri", zero);
Py_DECREF(zero);
if (wsgi_req->query_string_len > 0) {
zero = PyString_FromStringAndSize(wsgi_req->query_string, wsgi_req->query_string_len);
PyDict_SetItemString(wsgi_req->async_environ, "query_string", zero);
Py_DECREF(zero);
}
zero = PyString_FromStringAndSize(uwsgi_lower(wsgi_req->method, wsgi_req->method_len), wsgi_req->method_len);
PyDict_SetItemString(wsgi_req->async_environ, "method", zero);
Py_DECREF(zero);
if (wsgi_req->post_cl > 0) {
PyDict_SetItemString(wsgi_req->async_environ, "content_length", PyInt_FromLong(wsgi_req->post_cl));
if (wsgi_req->content_type_len > 0) {
zero = PyString_FromStringAndSize(wsgi_req->content_type, wsgi_req->content_type_len);
PyDict_SetItemString(wsgi_req->async_environ, "content_type", zero);
Py_DECREF(zero);
}
}
PyObject *headers = PyDict_New();
for (i = 0; i < wsgi_req->var_cnt; i += 2) {
#ifdef UWSGI_DEBUG
uwsgi_debug("%.*s: %.*s\n", wsgi_req->hvec[i].iov_len, wsgi_req->hvec[i].iov_base, wsgi_req->hvec[i+1].iov_len, wsgi_req->hvec[i+1].iov_base);
#endif
if (wsgi_req->hvec[i].iov_len < 6) continue;
if (!uwsgi_startswith(wsgi_req->hvec[i].iov_base, "HTTP_", 5)) {
(void) uwsgi_lower(wsgi_req->hvec[i].iov_base+5, wsgi_req->hvec[i].iov_len-5);
#ifdef PYTHREE
pydictkey = PyUnicode_DecodeLatin1(wsgi_req->hvec[i].iov_base+5, wsgi_req->hvec[i].iov_len-5, NULL);
pydictvalue = PyUnicode_DecodeLatin1(wsgi_req->hvec[i + 1].iov_base, wsgi_req->hvec[i + 1].iov_len, NULL);
#else
pydictkey = PyString_FromStringAndSize(wsgi_req->hvec[i].iov_base+5, wsgi_req->hvec[i].iov_len-5);
pydictvalue = PyString_FromStringAndSize(wsgi_req->hvec[i + 1].iov_base, wsgi_req->hvec[i + 1].iov_len);
#endif
PyObject *old_value = PyDict_GetItem(headers, pydictkey);
if (old_value) {
if (PyString_Check(old_value)) {
PyObject *new_value = PyList_New(0);
PyList_Append(new_value, old_value);
old_value = new_value;
PyDict_SetItem(headers, pydictkey, old_value);
Py_DECREF(old_value);
}
PyList_Append(old_value, pydictvalue);
}
else {
PyDict_SetItem(headers, pydictkey, pydictvalue);
}
Py_DECREF(pydictkey);
Py_DECREF(pydictvalue);
}
}
PyDict_SetItemString(wsgi_req->async_environ, "headers", headers);
Py_DECREF(headers);
// create wsgi.input custom object
wsgi_req->async_input = (PyObject *) PyObject_New(uwsgi_Input, &uwsgi_InputType);
((uwsgi_Input*)wsgi_req->async_input)->wsgi_req = wsgi_req;
//.........这里部分代码省略.........
示例2: sizeof
static PyObject *Py_FindObjects(PyObject *obj, PyObject *args)
{
PyArrayObject *input = NULL;
PyObject *result = NULL, *tuple = NULL, *start = NULL, *end = NULL;
PyObject *slc = NULL;
int jj;
long max_label;
maybelong ii, *regions = NULL;
if (!PyArg_ParseTuple(args, "O&l", NI_ObjectToInputArray, &input,
&max_label))
goto exit;
if (max_label < 0)
max_label = 0;
if (max_label > 0) {
if (input->nd > 0) {
regions = (maybelong*)malloc(2 * max_label * input->nd *
sizeof(maybelong));
} else {
regions = (maybelong*)malloc(max_label * sizeof(maybelong));
}
if (!regions) {
PyErr_NoMemory();
goto exit;
}
}
if (!NI_FindObjects(input, max_label, regions))
goto exit;
result = PyList_New(max_label);
if (!result) {
PyErr_NoMemory();
goto exit;
}
for(ii = 0; ii < max_label; ii++) {
maybelong idx = input->nd > 0 ? 2 * input->nd * ii : ii;
if (regions[idx] >= 0) {
PyObject *tuple = PyTuple_New(input->nd);
if (!tuple) {
PyErr_NoMemory();
goto exit;
}
for(jj = 0; jj < input->nd; jj++) {
start = PyLong_FromLong(regions[idx + jj]);
end = PyLong_FromLong(regions[idx + jj + input->nd]);
if (!start || !end) {
PyErr_NoMemory();
goto exit;
}
slc = PySlice_New(start, end, NULL);
if (!slc) {
PyErr_NoMemory();
goto exit;
}
Py_XDECREF(start);
Py_XDECREF(end);
start = end = NULL;
PyTuple_SetItem(tuple, jj, slc);
slc = NULL;
}
PyList_SetItem(result, ii, tuple);
tuple = NULL;
} else {
Py_INCREF(Py_None);
PyList_SetItem(result, ii, Py_None);
}
}
Py_INCREF(result);
exit:
Py_XDECREF(input);
Py_XDECREF(result);
Py_XDECREF(tuple);
Py_XDECREF(start);
Py_XDECREF(end);
Py_XDECREF(slc);
if (regions)
free(regions);
if (PyErr_Occurred()) {
Py_XDECREF(result);
return NULL;
} else {
return result;
}
}
示例3: get_dataset
static PyObject * get_dataset(PyObject *self, PyObject *args)
{
int i, j, k, num_atom;
double symprec;
SpglibDataset *dataset;
PyArrayObject* lattice_vectors;
PyArrayObject* atomic_positions;
PyArrayObject* atom_types;
PyObject* array, *vec, *mat, *rot, *trans, *wyckoffs, *equiv_atoms;
double *p_lattice;
double *p_positions;
double lattice[3][3];
double (*positions)[3];
int *types_int;
int *types;
if (!PyArg_ParseTuple(args, "OOOd",
&lattice_vectors,
&atomic_positions,
&atom_types,
&symprec)) {
return NULL;
}
p_lattice = (double(*))lattice_vectors->data;
p_positions = (double(*))atomic_positions->data;
num_atom = atom_types->dimensions[0];
positions = (double(*)[3]) malloc(sizeof(double[3]) * num_atom);
types_int = (int*)atom_types->data;
types = (int*) malloc(sizeof(int) * num_atom);
set_spglib_cell(lattice, positions, types, num_atom,
p_lattice, p_positions, types_int);
dataset = spg_get_dataset(lattice, positions, types, num_atom, symprec);
free(types);
free(positions);
array = PyList_New(10);
/* Space group number, international symbol, hall symbol */
PyList_SetItem(array, 0, PyInt_FromLong((long) dataset->spacegroup_number));
PyList_SetItem(array, 1, PyString_FromString(dataset->international_symbol));
PyList_SetItem(array, 2, PyInt_FromLong((long) dataset->hall_number));
PyList_SetItem(array, 3, PyString_FromString(dataset->hall_symbol));
/* Transformation matrix */
mat = PyList_New(3);
for (i = 0; i < 3; i++) {
vec = PyList_New(3);
for (j = 0; j < 3; j++) {
PyList_SetItem(vec, j,
PyFloat_FromDouble(dataset->transformation_matrix[i][j]));
}
PyList_SetItem(mat, i, vec);
}
PyList_SetItem(array, 4, mat);
/* Origin shift */
vec = PyList_New(3);
for (i = 0; i < 3; i++) {
PyList_SetItem(vec, i, PyFloat_FromDouble(dataset->origin_shift[i]));
}
PyList_SetItem(array, 5, vec);
/* Rotation matrices */
rot = PyList_New(dataset->n_operations);
for (i = 0; i < dataset->n_operations; i++) {
mat = PyList_New(3);
for (j = 0; j < 3; j++) {
vec = PyList_New(3);
for (k = 0; k < 3; k++) {
PyList_SetItem(vec, k,
PyInt_FromLong((long) dataset->rotations[i][j][k]));
}
PyList_SetItem(mat, j, vec);
}
PyList_SetItem(rot, i, mat);
}
PyList_SetItem(array, 6, rot);
/* Translation vectors */
trans = PyList_New(dataset->n_operations);
for (i = 0; i < dataset->n_operations; i++) {
vec = PyList_New(3);
for (j = 0; j < 3; j++) {
PyList_SetItem(vec, j, PyFloat_FromDouble(dataset->translations[i][j]));
}
PyList_SetItem(trans, i, vec);
}
PyList_SetItem(array, 7, trans);
/* Wyckoff letters, Equivalent atoms */
wyckoffs = PyList_New(dataset->n_atoms);
equiv_atoms = PyList_New(dataset->n_atoms);
for (i = 0; i < dataset->n_atoms; i++) {
PyList_SetItem(wyckoffs, i, PyInt_FromLong((long) dataset->wyckoffs[i]));
PyList_SetItem(equiv_atoms, i,
PyInt_FromLong((long) dataset->equivalent_atoms[i]));
}
PyList_SetItem(array, 8, wyckoffs);
//.........这里部分代码省略.........
示例4: PyList_New
PyObject *pygrpc_consume_ops(grpc_op *op, size_t nops) {
static const int TYPE_INDEX = 0;
static const int INITIAL_METADATA_INDEX = 1;
static const int TRAILING_METADATA_INDEX = 2;
static const int MESSAGE_INDEX = 3;
static const int STATUS_INDEX = 4;
static const int CANCELLED_INDEX = 5;
static const int OPRESULT_LENGTH = 6;
PyObject *list;
size_t i;
size_t j;
char *bytes;
size_t bytes_size;
PyObject *results = PyList_New(nops);
if (!results) {
return NULL;
}
for (i = 0; i < nops; ++i) {
PyObject *result = PyTuple_Pack(OPRESULT_LENGTH, Py_None, Py_None, Py_None,
Py_None, Py_None, Py_None);
PyTuple_SetItem(result, TYPE_INDEX, PyInt_FromLong(op[i].op));
switch(op[i].op) {
case GRPC_OP_RECV_INITIAL_METADATA:
PyTuple_SetItem(result, INITIAL_METADATA_INDEX,
list=PyList_New(op[i].data.recv_initial_metadata->count));
for (j = 0; j < op[i].data.recv_initial_metadata->count; ++j) {
grpc_metadata md = op[i].data.recv_initial_metadata->metadata[j];
PyList_SetItem(list, j, Py_BuildValue("ss#", md.key, md.value,
(Py_ssize_t)md.value_length));
}
break;
case GRPC_OP_RECV_MESSAGE:
if (*op[i].data.recv_message) {
pygrpc_byte_buffer_to_bytes(
*op[i].data.recv_message, &bytes, &bytes_size);
PyTuple_SetItem(result, MESSAGE_INDEX,
PyString_FromStringAndSize(bytes, bytes_size));
gpr_free(bytes);
} else {
PyTuple_SetItem(result, MESSAGE_INDEX, Py_BuildValue(""));
}
break;
case GRPC_OP_RECV_STATUS_ON_CLIENT:
PyTuple_SetItem(
result, TRAILING_METADATA_INDEX,
list = PyList_New(op[i].data.recv_status_on_client.trailing_metadata->count));
for (j = 0; j < op[i].data.recv_status_on_client.trailing_metadata->count; ++j) {
grpc_metadata md =
op[i].data.recv_status_on_client.trailing_metadata->metadata[j];
PyList_SetItem(list, j, Py_BuildValue("ss#", md.key, md.value,
(Py_ssize_t)md.value_length));
}
PyTuple_SetItem(
result, STATUS_INDEX, Py_BuildValue(
"is", *op[i].data.recv_status_on_client.status,
*op[i].data.recv_status_on_client.status_details));
break;
case GRPC_OP_RECV_CLOSE_ON_SERVER:
PyTuple_SetItem(
result, CANCELLED_INDEX,
PyBool_FromLong(*op[i].data.recv_close_on_server.cancelled));
break;
default:
break;
}
pygrpc_discard_op(op[i]);
PyList_SetItem(results, i, result);
}
return results;
}
示例5: decodeBuffer
/**
* Decode barcode from an image buffer. The supported data structure is DIB.
* It is necessary to re-construct input data for barcode detection.
*/
static PyObject *
decodeBuffer(PyObject *self, PyObject *args)
{
PyObject *o;
if (!PyArg_ParseTuple(args, "O", &o))
return NULL;
PyObject *ao = PyObject_GetAttrString(o, "__array_struct__");
PyObject *retval;
if ((ao == NULL) || !PyCObject_Check(ao)) {
PyErr_SetString(PyExc_TypeError, "object does not have array interface");
return NULL;
}
PyArrayInterface *pai = (PyArrayInterface*)PyCObject_AsVoidPtr(ao);
if (pai->two != 2) {
PyErr_SetString(PyExc_TypeError, "object does not have array interface");
Py_DECREF(ao);
return NULL;
}
// Construct data with header info and image data
char *buffer = (char*)pai->data; // The address of image data
int width = pai->shape[1]; // image width
int height = pai->shape[0]; // image height
int size = pai->strides[0] * pai->shape[0]; // image size = stride * height
char *total = (char *)malloc(size + 40); // buffer size = image size + header size
memset(total, 0, size + 40);
BITMAPINFOHEADER bitmap_info = {40, width, height, 0, 24, 0, size, 0, 0, 0, 0};
memcpy(total, &bitmap_info, 40);
// Copy image data to buffer from bottom to top
char *data = total + 40;
int stride = pai->strides[0];
int i = 1;
for (; i <= height; i++) {
memcpy(data, buffer + stride * (height - i), stride);
data += stride;
}
// Dynamsoft Barcode Reader initialization
__int64 llFormat = (OneD | QR_CODE | PDF417 | DATAMATRIX);
int iMaxCount = 0x7FFFFFFF;
ReaderOptions ro = {0};
pBarcodeResultArray pResults = NULL;
ro.llBarcodeFormat = llFormat;
ro.iMaxBarcodesNumPerPage = iMaxCount;
printf("width: %d, height: %d, size:%d\n", width, height, size);
int iRet = DBR_DecodeBuffer((unsigned char *)total, size + 40, &ro, &pResults);
printf("DBR_DecodeBuffer ret: %d\n", iRet);
free(total); // Do not forget to release the constructed buffer
// Get results
int count = pResults->iBarcodeCount;
pBarcodeResult* ppBarcodes = pResults->ppBarcodes;
pBarcodeResult tmp = NULL;
retval = PyList_New(count); // The returned Python object
PyObject* result = NULL;
i = 0;
for (; i < count; i++)
{
tmp = ppBarcodes[i];
result = PyString_FromString(tmp->pBarcodeData);
printf("result: %s\n", tmp->pBarcodeData);
PyList_SetItem(retval, i, Py_BuildValue("iN", (int)tmp->llFormat, result)); // Add results to list
}
// release memory
DBR_FreeBarcodeResults(&pResults);
Py_DECREF(ao);
return retval;
}
示例6: pysqlite_connection_init
//.........这里部分代码省略.........
if (rc != SQLITE_OK) {
_pysqlite_seterror(self->db, NULL);
return -1;
}
} else {
/* Create a pysqlite connection from a APSW connection */
class_attr = PyObject_GetAttrString(database, "__class__");
if (class_attr) {
class_attr_str = PyObject_Str(class_attr);
if (class_attr_str) {
if (strcmp(PyString_AsString(class_attr_str), "<type 'apsw.Connection'>") == 0) {
/* In the APSW Connection object, the first entry after
* PyObject_HEAD is the sqlite3* we want to get hold of.
* Luckily, this is the same layout as we have in our
* pysqlite_Connection */
self->db = ((pysqlite_Connection*)database)->db;
Py_INCREF(database);
self->apsw_connection = database;
is_apsw_connection = 1;
}
}
}
Py_XDECREF(class_attr_str);
Py_XDECREF(class_attr);
if (!is_apsw_connection) {
PyErr_SetString(PyExc_ValueError, "database parameter must be string or APSW Connection object");
return -1;
}
}
if (!isolation_level) {
isolation_level = PyString_FromString("");
if (!isolation_level) {
return -1;
}
} else {
Py_INCREF(isolation_level);
}
self->isolation_level = NULL;
pysqlite_connection_set_isolation_level(self, isolation_level);
Py_DECREF(isolation_level);
self->statement_cache = (pysqlite_Cache*)PyObject_CallFunction((PyObject*)&pysqlite_CacheType, "Oi", self, cached_statements);
if (PyErr_Occurred()) {
return -1;
}
self->created_statements = 0;
self->created_cursors = 0;
/* Create lists of weak references to statements/cursors */
self->statements = PyList_New(0);
self->cursors = PyList_New(0);
if (!self->statements || !self->cursors) {
return -1;
}
/* By default, the Cache class INCREFs the factory in its initializer, and
* decrefs it in its deallocator method. Since this would create a circular
* reference here, we're breaking it by decrementing self, and telling the
* cache class to not decref the factory (self) in its deallocator.
*/
self->statement_cache->decref_factory = 0;
Py_DECREF(self);
self->inTransaction = 0;
self->detect_types = detect_types;
self->timeout = timeout;
(void)sqlite3_busy_timeout(self->db, (int)(timeout*1000));
#ifdef WITH_THREAD
self->thread_ident = PyThread_get_thread_ident();
#endif
self->check_same_thread = check_same_thread;
self->function_pinboard = PyDict_New();
if (!self->function_pinboard) {
return -1;
}
self->collations = PyDict_New();
if (!self->collations) {
return -1;
}
self->Warning = pysqlite_Warning;
self->Error = pysqlite_Error;
self->InterfaceError = pysqlite_InterfaceError;
self->DatabaseError = pysqlite_DatabaseError;
self->DataError = pysqlite_DataError;
self->OperationalError = pysqlite_OperationalError;
self->IntegrityError = pysqlite_IntegrityError;
self->InternalError = pysqlite_InternalError;
self->ProgrammingError = pysqlite_ProgrammingError;
self->NotSupportedError = pysqlite_NotSupportedError;
return 0;
}
示例7: batch_select_aerospike_batch_get
/**
*******************************************************************************************************
* This function will get a batch of records from the Aeropike DB.
*
* @param err as_error object
* @param self AerospikeClient object
* @param py_keys The list of keys
* @param batch_policy_p as_policy_batch object
*
* Returns the record if key exists otherwise NULL.
*******************************************************************************************************
*/
static PyObject * batch_select_aerospike_batch_get(as_error *err, AerospikeClient * self, PyObject *py_keys, as_policy_batch * batch_policy_p, char **filter_bins, Py_ssize_t bins_size)
{
PyObject * py_recs = NULL;
as_batch batch;
bool batch_initialised = false;
// Convert python keys list to as_key ** and add it to as_batch.keys
// keys can be specified in PyList or PyTuple
if ( py_keys != NULL && PyList_Check(py_keys) ) {
Py_ssize_t size = PyList_Size(py_keys);
py_recs = PyList_New(size);
as_batch_init(&batch, size);
// Batch object initialised
batch_initialised = true;
for ( int i = 0; i < size; i++ ) {
PyObject * py_key = PyList_GetItem(py_keys, i);
if ( !PyTuple_Check(py_key) ) {
as_error_update(err, AEROSPIKE_ERR_PARAM, "Key should be a tuple.");
goto CLEANUP;
}
pyobject_to_key(err, py_key, as_batch_keyat(&batch, i));
if ( err->code != AEROSPIKE_OK ) {
goto CLEANUP;
}
}
}
else if ( py_keys != NULL && PyTuple_Check(py_keys) ) {
Py_ssize_t size = PyTuple_Size(py_keys);
py_recs = PyList_New(size);
as_batch_init(&batch, size);
// Batch object initialised
batch_initialised = true;
for ( int i = 0; i < size; i++ ) {
PyObject * py_key = PyTuple_GetItem(py_keys, i);
if ( !PyTuple_Check(py_key) ) {
as_error_update(err, AEROSPIKE_ERR_PARAM, "Key should be a tuple.");
goto CLEANUP;
}
pyobject_to_key(err, py_key, as_batch_keyat(&batch, i));
if ( err->code != AEROSPIKE_OK ) {
goto CLEANUP;
}
}
}
else {
as_error_update(err, AEROSPIKE_ERR_PARAM, "Keys should be specified as a list or tuple.");
goto CLEANUP;
}
// Invoke C-client API
aerospike_batch_get_bins(self->as, err, batch_policy_p,
&batch, (const char **) filter_bins, bins_size,
(aerospike_batch_read_callback) batch_select_cb,
py_recs);
CLEANUP:
if (batch_initialised == true) {
// We should destroy batch object as we are using 'as_batch_init' for initialisation
// Also, pyobject_to_key is soing strdup() in case of Unicode. So, object destruction
// is necessary.
as_batch_destroy(&batch);
}
return py_recs;
}
示例8: _buffer_get_info
/* Get buffer info from the global dictionary */
static _buffer_info_t*
_buffer_get_info(PyObject *arr)
{
PyObject *key = NULL, *item_list = NULL, *item = NULL;
_buffer_info_t *info = NULL, *old_info = NULL;
if (_buffer_info_cache == NULL) {
_buffer_info_cache = PyDict_New();
if (_buffer_info_cache == NULL) {
return NULL;
}
}
/* Compute information */
info = _buffer_info_new((PyArrayObject*)arr);
if (info == NULL) {
return NULL;
}
/* Check if it is identical with an old one; reuse old one, if yes */
key = PyLong_FromVoidPtr((void*)arr);
if (key == NULL) {
goto fail;
}
item_list = PyDict_GetItem(_buffer_info_cache, key);
if (item_list != NULL) {
Py_INCREF(item_list);
if (PyList_GET_SIZE(item_list) > 0) {
item = PyList_GetItem(item_list, PyList_GET_SIZE(item_list) - 1);
old_info = (_buffer_info_t*)PyLong_AsVoidPtr(item);
if (_buffer_info_cmp(info, old_info) == 0) {
_buffer_info_free(info);
info = old_info;
}
}
}
else {
item_list = PyList_New(0);
if (item_list == NULL) {
goto fail;
}
if (PyDict_SetItem(_buffer_info_cache, key, item_list) != 0) {
goto fail;
}
}
if (info != old_info) {
/* Needs insertion */
item = PyLong_FromVoidPtr((void*)info);
if (item == NULL) {
goto fail;
}
PyList_Append(item_list, item);
Py_DECREF(item);
}
Py_DECREF(item_list);
Py_DECREF(key);
return info;
fail:
if (info != NULL && info != old_info) {
_buffer_info_free(info);
}
Py_XDECREF(item_list);
Py_XDECREF(key);
return NULL;
}
示例9: PLy_spi_execute_fetch_result
static PyObject *
PLy_spi_execute_fetch_result(SPITupleTable *tuptable, int rows, int status)
{
PLyResultObject *result;
volatile MemoryContext oldcontext;
result = (PLyResultObject *) PLy_result_new();
Py_DECREF(result->status);
result->status = PyInt_FromLong(status);
if (status > 0 && tuptable == NULL)
{
Py_DECREF(result->nrows);
result->nrows = PyInt_FromLong(rows);
}
else if (status > 0 && tuptable != NULL)
{
PLyTypeInfo args;
int i;
Py_DECREF(result->nrows);
result->nrows = PyInt_FromLong(rows);
PLy_typeinfo_init(&args);
oldcontext = CurrentMemoryContext;
PG_TRY();
{
MemoryContext oldcontext2;
if (rows)
{
Py_DECREF(result->rows);
result->rows = PyList_New(rows);
PLy_input_tuple_funcs(&args, tuptable->tupdesc);
for (i = 0; i < rows; i++)
{
PyObject *row = PLyDict_FromTuple(&args,
tuptable->vals[i],
tuptable->tupdesc);
PyList_SetItem(result->rows, i, row);
}
}
/*
* Save tuple descriptor for later use by result set metadata
* functions. Save it in TopMemoryContext so that it survives
* outside of an SPI context. We trust that PLy_result_dealloc()
* will clean it up when the time is right. (Do this as late as
* possible, to minimize the number of ways the tupdesc could get
* leaked due to errors.)
*/
oldcontext2 = MemoryContextSwitchTo(TopMemoryContext);
result->tupdesc = CreateTupleDescCopy(tuptable->tupdesc);
MemoryContextSwitchTo(oldcontext2);
}
PG_CATCH();
{
MemoryContextSwitchTo(oldcontext);
PLy_typeinfo_dealloc(&args);
SPI_freetuptable(tuptable);
Py_DECREF(result);
PG_RE_THROW();
}
PG_END_TRY();
PLy_typeinfo_dealloc(&args);
SPI_freetuptable(tuptable);
}
return (PyObject *) result;
}
示例10: watchdog_FSEventStreamCallback
/**
* This is the callback passed to the FSEvents API, which calls
* the Python callback function, in turn, by passing in event data
* as Python objects.
*
* :param stream_ref:
* A pointer to an ``FSEventStream`` instance.
* :param stream_callback_info_ref:
* Callback context information passed by the FSEvents API.
* This contains a reference to the Python callback that this
* function calls in turn with information about the events.
* :param num_events:
* An unsigned integer representing the number of events
* captured by the FSEvents API.
* :param event_paths:
* An array of NUL-terminated C strings representing event paths.
* :param event_flags:
* An array of ``FSEventStreamEventFlags`` unsigned integral
* mask values.
* :param event_ids:
* An array of 64-bit unsigned integers representing event
* identifiers.
*/
static void
watchdog_FSEventStreamCallback(ConstFSEventStreamRef stream_ref,
StreamCallbackInfo *stream_callback_info_ref,
size_t num_events,
const char *event_paths[],
const FSEventStreamEventFlags event_flags[],
const FSEventStreamEventId event_ids[])
{
UNUSED(stream_ref);
UNUSED(event_ids);
size_t i = 0;
PyObject *callback_result = NULL;
PyObject *path = NULL;
PyObject *flags = NULL;
PyObject *py_event_flags = NULL;
PyObject *py_event_paths = NULL;
PyThreadState *saved_thread_state = NULL;
/* Acquire interpreter lock and save original thread state. */
PyGILState_STATE gil_state = PyGILState_Ensure();
saved_thread_state = PyThreadState_Swap(stream_callback_info_ref->thread_state);
/* Convert event flags and paths to Python ints and strings. */
py_event_paths = PyList_New(num_events);
py_event_flags = PyList_New(num_events);
if (G_NOT(py_event_paths && py_event_flags))
{
Py_DECREF(py_event_paths);
Py_DECREF(py_event_flags);
return /*NULL*/;
}
for (i = 0; i < num_events; ++i)
{
#if PY_MAJOR_VERSION >= 3
path = PyUnicode_FromString(event_paths[i]);
flags = PyLong_FromLong(event_flags[i]);
#else
path = PyString_FromString(event_paths[i]);
flags = PyInt_FromLong(event_flags[i]);
#endif
if (G_NOT(path && flags))
{
Py_DECREF(py_event_paths);
Py_DECREF(py_event_flags);
return /*NULL*/;
}
PyList_SET_ITEM(py_event_paths, i, path);
PyList_SET_ITEM(py_event_flags, i, flags);
}
/* Call the Python callback function supplied by the stream information
* struct. The Python callback function should accept two arguments,
* both being Python lists:
*
* def python_callback(event_paths, event_flags):
* pass
*/
callback_result = \
PyObject_CallFunction(stream_callback_info_ref->python_callback,
"OO", py_event_paths, py_event_flags);
if (G_IS_NULL(callback_result))
{
if (G_NOT(PyErr_Occurred()))
{
PyErr_SetString(PyExc_ValueError, ERROR_CANNOT_CALL_CALLBACK);
}
CFRunLoopStop(stream_callback_info_ref->run_loop_ref);
}
/* Release the lock and restore thread state. */
PyThreadState_Swap(saved_thread_state);
PyGILState_Release(gil_state);
}
示例11: PyCom_BuildPyException
PyObject *PyRecord::getattro(PyObject *self, PyObject *obname)
{
PyObject *res;
PyRecord *pyrec = (PyRecord *)self;
char *name=PYWIN_ATTR_CONVERT(obname);
if (name==NULL)
return NULL;
if (strcmp(name, "__members__")==0) {
ULONG cnames = 0;
HRESULT hr = pyrec->pri->GetFieldNames(&cnames, NULL);
if (FAILED(hr))
return PyCom_BuildPyException(hr, pyrec->pri, IID_IRecordInfo);
BSTR *strs = (BSTR *)malloc(sizeof(BSTR) * cnames);
if (strs==NULL)
return PyErr_NoMemory();
hr = pyrec->pri->GetFieldNames(&cnames, strs);
if (FAILED(hr)) {
free(strs);
return PyCom_BuildPyException(hr, pyrec->pri, IID_IRecordInfo);
}
res = PyList_New(cnames);
for (ULONG i=0;i<cnames && res != NULL;i++) {
PyObject *item = PyWinCoreString_FromString(strs[i]);
SysFreeString(strs[i]);
if (item==NULL) {
Py_DECREF(res);
res = NULL;
} else
PyList_SET_ITEM(res, i, item); // ref count swallowed.
}
free(strs);
return res;
}
res = PyObject_GenericGetAttr(self, obname);
if (res != NULL)
return res;
PyErr_Clear();
WCHAR *wname;
if (!PyWinObject_AsWCHAR(obname, &wname))
return NULL;
VARIANT vret;
VariantInit(&vret);
void *sub_data = NULL;
PY_INTERFACE_PRECALL;
HRESULT hr = pyrec->pri->GetFieldNoCopy(pyrec->pdata, wname, &vret, &sub_data);
PyWinObject_FreeWCHAR(wname);
PY_INTERFACE_POSTCALL;
if (FAILED(hr)) {
if (hr == TYPE_E_FIELDNOTFOUND){
// This is slightly suspect - throwing a unicode
// object for an AttributeError in py2k - but this
// is the value we asked COM for, so it makes sense...
// (and PyErr_Format doesn't handle unicode in py2x)
PyErr_SetObject(PyExc_AttributeError, obname);
return NULL;
}
return PyCom_BuildPyException(hr, pyrec->pri, IID_IRecordInfo);
}
// Short-circuit sub-structs and arrays here, so we dont allocate a new chunk
// of memory and copy it - we need sub-structs to persist.
if (V_VT(&vret)==(VT_BYREF | VT_RECORD))
return new PyRecord(V_RECORDINFO(&vret), V_RECORD(&vret), pyrec->owner);
else if (V_VT(&vret)==(VT_BYREF | VT_ARRAY | VT_RECORD)) {
SAFEARRAY *psa = *V_ARRAYREF(&vret);
int d = SafeArrayGetDim(psa);
if (sub_data==NULL)
return PyErr_Format(PyExc_RuntimeError, "Did not get a buffer for the array!");
if (SafeArrayGetDim(psa) != 1)
return PyErr_Format(PyExc_TypeError, "Only support single dimensional arrays of records");
IRecordInfo *sub = NULL;
long ubound, lbound, nelems;
int i;
BYTE *this_data;
PyObject *ret_tuple = NULL;
ULONG element_size = 0;
hr = SafeArrayGetUBound(psa, 1, &ubound);
if (FAILED(hr)) goto array_end;
hr = SafeArrayGetLBound(psa, 1, &lbound);
if (FAILED(hr)) goto array_end;
hr = SafeArrayGetRecordInfo(psa, &sub);
if (FAILED(hr)) goto array_end;
hr = sub->GetSize(&element_size);
if (FAILED(hr)) goto array_end;
nelems = ubound-lbound;
ret_tuple = PyTuple_New(nelems);
if (ret_tuple==NULL) goto array_end;
this_data = (BYTE *)sub_data;
for (i=0;i<nelems;i++) {
PyTuple_SET_ITEM(ret_tuple, i, new PyRecord(sub, this_data, pyrec->owner));
this_data += element_size;
}
array_end:
if (sub)
sub->Release();
//.........这里部分代码省略.........
示例12: SpiDev_xfer
//.........这里部分代码省略.........
if (!PyList_Check(list)) {
PyErr_SetString(PyExc_TypeError, wrmsg);
return NULL;
}
if ((len = PyList_GET_SIZE(list)) > SPIDEV_MAXPATH) {
PyErr_SetString(PyExc_OverflowError, wrmsg);
return NULL;
}
txbuf = malloc(sizeof(__u8) * len);
rxbuf = malloc(sizeof(__u8) * len);
#ifdef SPIDEV_SINGLE
xferptr = (struct spi_ioc_transfer*) malloc(sizeof(struct spi_ioc_transfer) * len);
for (ii = 0; ii < len; ii++) {
PyObject *val = PyList_GET_ITEM(list, ii);
if (!PyLong_Check(val)) {
PyErr_SetString(PyExc_TypeError, wrmsg);
free(xferptr);
free(txbuf);
free(rxbuf);
return NULL;
}
txbuf[ii] = (__u8)PyLong_AS_LONG(val);
xferptr[ii].tx_buf = (unsigned long)&txbuf[ii];
xferptr[ii].rx_buf = (unsigned long)&rxbuf[ii];
xferptr[ii].len = 1;
xferptr[ii].delay_usecs = delay;
xferptr[ii].speed_hz = speed_hz ? speed_hz : self->max_speed_hz;
xferptr[ii].bits_per_word = bits_per_word ? bits_per_word : self->bits_per_word;
#ifdef SPI_IOC_WR_MODE32
xferptr[ii].tx_nbits = 0;
#endif
#ifdef SPI_IOC_RD_MODE32
xferptr[ii].rx_nbits = 0;
#endif
}
status = ioctl(self->fd, SPI_IOC_MESSAGE(len), xferptr);
if (status < 0) {
PyErr_SetFromErrno(PyExc_IOError);
free(xferptr);
free(txbuf);
free(rxbuf);
return NULL;
}
#else
for (ii = 0; ii < len; ii++) {
PyObject *val = PyList_GET_ITEM(list, ii);
if (!PyLong_Check(val)) {
PyErr_SetString(PyExc_TypeError, wrmsg);
free(txbuf);
free(rxbuf);
return NULL;
}
txbuf[ii] = (__u8)PyLong_AS_LONG(val);
}
xfer.tx_buf = (unsigned long)txbuf;
xfer.rx_buf = (unsigned long)rxbuf;
xfer.len = len;
xfer.delay_usecs = delay_usecs;
xfer.speed_hz = speed_hz ? speed_hz : self->max_speed_hz;
xfer.bits_per_word = bits_per_word ? bits_per_word : self->bits_per_word;
#ifdef SPI_IOC_WR_MODE32
xfer.tx_nbits = 0;
#endif
#ifdef SPI_IOC_RD_MODE32
xfer.rx_nbits = 0;
#endif
status = ioctl(self->fd, SPI_IOC_MESSAGE(1), &xfer);
if (status < 0) {
PyErr_SetFromErrno(PyExc_IOError);
free(txbuf);
free(rxbuf);
return NULL;
}
#endif
list = PyList_New(len);
for (ii = 0; ii < len; ii++) {
PyObject *val = Py_BuildValue("l", (long)rxbuf[ii]);
PyList_SET_ITEM(list, ii, val);
}
// WA:
// in CS_HIGH mode CS isn't pulled to low after transfer, but after read
// reading 0 bytes doesnt matter but brings cs down
// tomdean:
// Stop generating an extra CS except in mode CS_HOGH
if (self->mode & SPI_CS_HIGH) status = read(self->fd, &rxbuf[0], 0);
free(txbuf);
free(rxbuf);
return list;
}
示例13: PyErr_Format
PyObject *wsgi_convert_headers_to_bytes(PyObject *headers)
{
PyObject *result = NULL;
int i;
long size;
if (!PyList_Check(headers)) {
PyErr_Format(PyExc_TypeError, "expected list object for headers, "
"value of type %.200s found", headers->ob_type->tp_name);
return 0;
}
size = PyList_Size(headers);
result = PyList_New(size);
for (i = 0; i < size; i++) {
PyObject *header = NULL;
PyObject *header_name = NULL;
PyObject *header_value = NULL;
PyObject *header_name_as_bytes = NULL;
PyObject *header_value_as_bytes = NULL;
PyObject *result_tuple = NULL;
header = PyList_GetItem(headers, i);
if (!PyTuple_Check(header)) {
PyErr_Format(PyExc_TypeError, "list of tuple values "
"expected for headers, value of type %.200s found",
header->ob_type->tp_name);
Py_DECREF(result);
return 0;
}
if (PyTuple_Size(header) != 2) {
PyErr_Format(PyExc_ValueError, "tuple of length 2 "
"expected for header, length is %d",
(int)PyTuple_Size(header));
Py_DECREF(result);
return 0;
}
result_tuple = PyTuple_New(2);
PyList_SET_ITEM(result, i, result_tuple);
header_name = PyTuple_GetItem(header, 0);
header_value = PyTuple_GetItem(header, 1);
header_name_as_bytes = wsgi_convert_string_to_bytes(header_name);
if (!header_name_as_bytes)
goto failure;
PyTuple_SET_ITEM(result_tuple, 0, header_name_as_bytes);
if (!wsgi_validate_header_name(header_name_as_bytes))
goto failure;
header_value_as_bytes = wsgi_convert_string_to_bytes(header_value);
if (!header_value_as_bytes)
goto failure;
PyTuple_SET_ITEM(result_tuple, 1, header_value_as_bytes);
if (!wsgi_validate_header_value(header_value_as_bytes))
goto failure;
}
return result;
failure:
Py_DECREF(result);
return NULL;
}
示例14: SpiDev_xfer2
static PyObject *
SpiDev_xfer2(SpiDevObject *self, PyObject *args)
{
static char *msg = "Argument must be a list of at least one, "
"but not more than 4096 integers";
int status;
uint16_t delay_usecs = 0;
uint32_t speed_hz = 0;
uint8_t bits_per_word = 0;
uint16_t ii, len;
PyObject *list;
struct spi_ioc_transfer xfer;
memset(&xfer, 0, sizeof(xfer));
uint8_t *txbuf, *rxbuf;
if (!PyArg_ParseTuple(args, "O|IHB:xfer2", &list, &speed_hz, &delay_usecs, &bits_per_word))
return NULL;
if (!PyList_Check(list)) {
PyErr_SetString(PyExc_TypeError, wrmsg);
return NULL;
}
if ((len = PyList_GET_SIZE(list)) > SPIDEV_MAXPATH) {
PyErr_SetString(PyExc_OverflowError, wrmsg);
return NULL;
}
txbuf = malloc(sizeof(__u8) * len);
rxbuf = malloc(sizeof(__u8) * len);
for (ii = 0; ii < len; ii++) {
PyObject *val = PyList_GET_ITEM(list, ii);
if (!PyLong_Check(val)) {
PyErr_SetString(PyExc_TypeError, msg);
free(txbuf);
free(rxbuf);
return NULL;
}
txbuf[ii] = (__u8)PyLong_AS_LONG(val);
}
xfer.tx_buf = (unsigned long)txbuf;
xfer.rx_buf = (unsigned long)rxbuf;
xfer.len = len;
xfer.delay_usecs = delay_usecs;
xfer.speed_hz = speed_hz ? speed_hz : self->max_speed_hz;
xfer.bits_per_word = bits_per_word ? bits_per_word : self->bits_per_word;
status = ioctl(self->fd, SPI_IOC_MESSAGE(1), &xfer);
if (status < 0) {
PyErr_SetFromErrno(PyExc_IOError);
free(txbuf);
free(rxbuf);
return NULL;
}
list = PyList_New(len);
for (ii = 0; ii < len; ii++) {
PyObject *val = Py_BuildValue("l", (long)rxbuf[ii]);
PyList_SET_ITEM(list, ii, val);
}
// WA:
// in CS_HIGH mode CS isnt pulled to low after transfer
// reading 0 bytes doesn't really matter but brings CS down
// tomdean:
// Stop generating an extra CS except in mode CS_HOGH
if (self->mode & SPI_CS_HIGH) status = read(self->fd, &rxbuf[0], 0);
free(txbuf);
free(rxbuf);
return list;
}
示例15: batch_select_aerospike_batch_read
/**
*******************************************************************************************************
* This function will get a batch of records from the Aeropike DB.
*
* @param err as_error object
* @param self AerospikeClient object
* @param py_keys The list of keys
* @param batch_policy_p as_policy_batch object
*
* Returns the record if key exists otherwise NULL.
*******************************************************************************************************
*/
static PyObject * batch_select_aerospike_batch_read(as_error *err, AerospikeClient * self, PyObject *py_keys, as_policy_batch * batch_policy_p, char** filter_bins, Py_ssize_t bins_size)
{
PyObject * py_recs = NULL;
as_batch_read_records records;
as_batch_read_record* record = NULL;
bool batch_initialised = false;
// Convert python keys list to as_key ** and add it to as_batch.keys
// keys can be specified in PyList or PyTuple
if ( py_keys != NULL && PyList_Check(py_keys) ) {
Py_ssize_t size = PyList_Size(py_keys);
py_recs = PyList_New(size);
as_batch_read_inita(&records, size);
// Batch object initialised
batch_initialised = true;
for ( int i = 0; i < size; i++ ) {
PyObject * py_key = PyList_GetItem(py_keys, i);
if ( !PyTuple_Check(py_key) ) {
as_error_update(err, AEROSPIKE_ERR_PARAM, "Key should be a tuple.");
goto CLEANUP;
}
record = as_batch_read_reserve(&records);
pyobject_to_key(err, py_key, &record->key);
if (bins_size) {
record->bin_names = filter_bins;
record->n_bin_names = bins_size;
} else {
record->read_all_bins = true;
}
if ( err->code != AEROSPIKE_OK ) {
goto CLEANUP;
}
}
}
else if ( py_keys != NULL && PyTuple_Check(py_keys) ) {
Py_ssize_t size = PyTuple_Size(py_keys);
py_recs = PyList_New(size);
as_batch_read_inita(&records, size);
// Batch object initialised
batch_initialised = true;
for ( int i = 0; i < size; i++ ) {
PyObject * py_key = PyTuple_GetItem(py_keys, i);
if ( !PyTuple_Check(py_key) ) {
as_error_update(err, AEROSPIKE_ERR_PARAM, "Key should be a tuple.");
goto CLEANUP;
}
record = as_batch_read_reserve(&records);
pyobject_to_key(err, py_key, &record->key);
if (bins_size) {
record->bin_names = filter_bins;
record->n_bin_names = bins_size;
} else {
record->read_all_bins = true;
}
if ( err->code != AEROSPIKE_OK ) {
goto CLEANUP;
}
}
}
else {
as_error_update(err, AEROSPIKE_ERR_PARAM, "Keys should be specified as a list or tuple.");
goto CLEANUP;
}
// Invoke C-client API
if (aerospike_batch_read(self->as, err, batch_policy_p, &records) != AEROSPIKE_OK)
{
goto CLEANUP;
}
batch_select_recs(err, &records, &py_recs);
CLEANUP:
//.........这里部分代码省略.........