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

C++ PyTuple_SetItem函数代码示例

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

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



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

示例1: python_orblag

static PyObject *
python_orblag( PyObject *self, PyObject *args ) {
	char	*usage = "Usage: _orblag(orb, match, reject)\n";
	int	orbfd;
	char	*match = 0;
	char	*reject = 0;
	char	err[STRSZ];
	double	rc;
	int	ilaggard;
	int	nlaggards;
	ClientLag *cl = 0;
	Laggards *laggards = 0;
	PyObject *laggards_obj;
	PyObject *clientlag_obj;
	PyObject *obj;

	if( ! PyArg_ParseTuple( args, "izz", &orbfd, &match, &reject) ) {

		if( ! PyErr_Occurred() ) {

			PyErr_SetString( PyExc_RuntimeError, usage );
		}

		return NULL;
	}

	rc = orblag( orbfd, match, reject, &laggards );

	if( rc < 0 ) {

		sprintf( err, "Error: orblag returned %f\n", rc );

		PyErr_SetString( PyExc_RuntimeError, err );

		return NULL;
	}

	nlaggards = maxtbl( laggards->list );

	laggards_obj = PyTuple_New( nlaggards );

	for( ilaggard = 0; ilaggard < nlaggards; ilaggard++ ) {

		cl = gettbl( laggards->list, ilaggard );

		clientlag_obj = PyTuple_New( 5 );

		PyTuple_SetItem( clientlag_obj, 0, PyFloat_FromDouble( cl->lag ) );
		PyTuple_SetItem( clientlag_obj, 1, PyInt_FromLong( (long) cl->thread ) );
		PyTuple_SetItem( clientlag_obj, 2, PyInt_FromLong( (long) cl->pktid ) );
		PyTuple_SetItem( clientlag_obj, 3, PyString_FromString( cl->who ) );
		PyTuple_SetItem( clientlag_obj, 4, PyString_FromString( cl->what ) );

		PyTuple_SetItem( laggards_obj, ilaggard, clientlag_obj );
	}

	obj = Py_BuildValue( "iiiiO", laggards->oldest,
				      laggards->newest,
				      laggards->maxpktid, 
				      laggards->range, 
				      laggards_obj );

	freeLaggards( laggards );

	return obj;
}
开发者ID:vonseg,项目名称:antelope_contrib,代码行数:66,代码来源:_orb.c


示例2: interpret_notification

void interpret_notification(PyObject* dict, const void *pnotif, int size)
{
	const union sctp_notification *notif = pnotif;
	PyDict_SetItemString(dict, "type", PyInt_FromLong(notif->sn_header.sn_type));
	PyDict_SetItemString(dict, "flags", PyInt_FromLong(notif->sn_header.sn_flags));
	PyDict_SetItemString(dict, "length", PyInt_FromLong(notif->sn_header.sn_length));

	switch (notif->sn_header.sn_type) {
	case SCTP_ASSOC_CHANGE:
		{
		const struct sctp_assoc_change* n = &(notif->sn_assoc_change);
		PyDict_SetItemString(dict, "state", PyInt_FromLong(n->sac_state));
		PyDict_SetItemString(dict, "error", PyInt_FromLong(n->sac_error));
		PyDict_SetItemString(dict, "outbound_streams", PyInt_FromLong(n->sac_outbound_streams));
		PyDict_SetItemString(dict, "inbound_streams", PyInt_FromLong(n->sac_inbound_streams));
		PyDict_SetItemString(dict, "assoc_id", PyInt_FromLong(n->sac_assoc_id));
		}
		break;
	case SCTP_PEER_ADDR_CHANGE: 
		{
		const struct sctp_paddr_change* n = &(notif->sn_paddr_change);
		char caddr[256];
		int family;
		int len;
		int port;
		PyObject* oaddr;

		if (from_sockaddr((struct sockaddr*) &(n->spc_aaddr), &family, &len, &port, 
									caddr, sizeof(caddr))) {
			oaddr = PyTuple_New(2);
			PyTuple_SetItem(oaddr, 0, PyString_FromString(caddr));
			PyTuple_SetItem(oaddr, 1, PyInt_FromLong(port));
		} else {
			// something went wrong
			oaddr = Py_None;
			Py_INCREF(Py_None);
		}

		PyDict_SetItemString(dict, "addr", oaddr);
		PyDict_SetItemString(dict, "state", PyInt_FromLong(n->spc_state));
		PyDict_SetItemString(dict, "error", PyInt_FromLong(n->spc_error));
		PyDict_SetItemString(dict, "assoc_id", PyInt_FromLong(n->spc_assoc_id));
		}
		break;
	case SCTP_SEND_FAILED:
		{
		const struct sctp_send_failed* n = &(notif->sn_send_failed);
		const char* cdata = ((char*) notif) + sizeof(struct sctp_send_failed);
		int ldata = size - sizeof(struct sctp_send_failed);

		if (ldata >= 0) {
			PyObject* info = PyDict_New();
			interpret_sndrcvinfo(info, &(n->ssf_info));
			PyDict_SetItemString(dict, "_info", info);
			PyDict_SetItemString(dict, "error", PyInt_FromLong(n->ssf_error));
			PyDict_SetItemString(dict, "assoc_id", PyInt_FromLong(n->ssf_assoc_id));
			PyDict_SetItemString(dict, "data", PyString_FromStringAndSize(cdata, ldata));
		}
		}
		break;
	case SCTP_REMOTE_ERROR:
		{
		const struct sctp_remote_error* n = &(notif->sn_remote_error);
		const char* cdata = ((char*) notif) + sizeof(struct sctp_remote_error);
		int ldata = size - sizeof(struct sctp_remote_error);
		
		if (ldata >= 0) {
			PyDict_SetItemString(dict, "error", PyInt_FromLong(n->sre_error));
			PyDict_SetItemString(dict, "assoc_id", PyInt_FromLong(n->sre_assoc_id));
			PyDict_SetItemString(dict, "data", PyString_FromStringAndSize(cdata, ldata));
		}
		}
		break;
	case SCTP_SHUTDOWN_EVENT:
		{
		const struct sctp_shutdown_event* n = &(notif->sn_shutdown_event);
		PyDict_SetItemString(dict, "assoc_id", PyInt_FromLong(n->sse_assoc_id));
		}
		break;
	case SCTP_PARTIAL_DELIVERY_EVENT:
		{
		const struct sctp_pdapi_event* n = &(notif->sn_pdapi_event);
		PyDict_SetItemString(dict, "indication", PyInt_FromLong(n->pdapi_indication));
		PyDict_SetItemString(dict, "assoc_id", PyInt_FromLong(n->pdapi_assoc_id));
		}
		break;
	case SCTP_ADAPTATION_INDICATION:
		{
		const struct sctp_adaptation_event* n = &(notif->sn_adaptation_event);
		PyDict_SetItemString(dict, "adaptation_ind", PyInt_FromLong(n->sai_adaptation_ind));
		PyDict_SetItemString(dict, "assoc_id", PyInt_FromLong(n->sai_assoc_id));
		}
		break;
	}
}
开发者ID:BillTheBest,项目名称:pysctp,代码行数:95,代码来源:_sctp.c


示例3: get_status

static PyObject* get_status(PyObject* dummy, PyObject* args)
{
	PyObject* ret = 0;
	PyObject* dict;
	PyObject* dict2;
	PyObject* oassoc_id;

	PyObject* oaddr;
	char caddr[256];
	int family, len, port;

	int fd;
	struct sctp_status v;
	socklen_t lv = sizeof(v);
	int ok;
	
	ok = PyArg_ParseTuple(args, "iOO", &fd, &dict, &dict2) && \
	     					PyDict_Check(dict) && PyDict_Check(dict2);
	ok = ok && (oassoc_id = PyDict_GetItemString(dict, "assoc_id"));
	ok = ok && PyInt_Check(oassoc_id);

	if (! ok) {
		return ret;
	}

	bzero(&v, sizeof(v));
	v.sstat_assoc_id = PyInt_AsLong(oassoc_id);

	if (getsockopt(fd, SOL_SCTP, SCTP_STATUS, &v, &lv)) {
		PyErr_SetFromErrno(PyExc_IOError);
	} else {
		PyDict_SetItemString(dict, "state", PyInt_FromLong(v.sstat_state));
		PyDict_SetItemString(dict, "rwnd", PyInt_FromLong(v.sstat_rwnd));
		PyDict_SetItemString(dict, "unackdata", PyInt_FromLong(v.sstat_unackdata));
		PyDict_SetItemString(dict, "penddata", PyInt_FromLong(v.sstat_penddata));
		PyDict_SetItemString(dict, "instrms", PyInt_FromLong(v.sstat_instrms));
		PyDict_SetItemString(dict, "outstrms", PyInt_FromLong(v.sstat_outstrms));
		PyDict_SetItemString(dict, "fragmentation_point", PyInt_FromLong(v.sstat_fragmentation_point));

		if (from_sockaddr((struct sockaddr*) &(v.sstat_primary.spinfo_address), &family, 
					&len, &port, caddr, sizeof(caddr))) {
			oaddr = PyTuple_New(2);
			PyTuple_SetItem(oaddr, 0, PyString_FromString(caddr));
			PyTuple_SetItem(oaddr, 1, PyInt_FromLong(port));
		} else {
			// something went wrong
			oaddr = Py_None;
			Py_INCREF(Py_None);
		}
		
		PyDict_SetItemString(dict2, "sockaddr", oaddr);
		PyDict_SetItemString(dict2, "assoc_id", PyInt_FromLong(v.sstat_primary.spinfo_assoc_id));
		PyDict_SetItemString(dict2, "state", PyInt_FromLong(v.sstat_primary.spinfo_state));
		PyDict_SetItemString(dict2, "cwnd", PyInt_FromLong(v.sstat_primary.spinfo_cwnd));
		PyDict_SetItemString(dict2, "srtt", PyInt_FromLong(v.sstat_primary.spinfo_srtt));
		PyDict_SetItemString(dict2, "rto", PyInt_FromLong(v.sstat_primary.spinfo_rto));
		PyDict_SetItemString(dict2, "mtu", PyInt_FromLong(v.sstat_primary.spinfo_mtu));
		ret = Py_None; Py_INCREF(ret);
	}

	return ret;
}
开发者ID:BillTheBest,项目名称:pysctp,代码行数:62,代码来源:_sctp.c


示例4: uwsgi_python_setup_thread

void *uwsgi_python_tracebacker_thread(void *foobar) {

	struct iovec iov[11];

	PyObject *new_thread = uwsgi_python_setup_thread("uWSGITraceBacker");
	if (!new_thread) return NULL;

	struct sockaddr_un so_sun;
	socklen_t so_sun_len = 0;

	char *str_wid = uwsgi_num2str(uwsgi.mywid);
	char *sock_path = uwsgi_concat2(up.tracebacker, str_wid);

	int current_defer_accept = uwsgi.no_defer_accept;
        uwsgi.no_defer_accept = 1;
	int fd = bind_to_unix(sock_path, uwsgi.listen_queue, uwsgi.chmod_socket, uwsgi.abstract_socket);
	if (fd < 0) {
		uwsgi.no_defer_accept = current_defer_accept;
		free(str_wid);
		free(sock_path);
		return NULL;
	}
        uwsgi.no_defer_accept = current_defer_accept;

	PyObject *traceback_module = PyImport_ImportModule("traceback");
	if (!traceback_module) {
		free(str_wid);
		free(sock_path);
		close(fd);
		return NULL;
	}
	PyObject *traceback_dict = PyModule_GetDict(traceback_module);
	PyObject *extract_stack = PyDict_GetItemString(traceback_dict, "extract_stack");

	PyObject *sys_module = PyImport_ImportModule("sys");
	PyObject *sys_dict = PyModule_GetDict(sys_module);

	PyObject *_current_frames = PyDict_GetItemString(sys_dict, "_current_frames");

	uwsgi_log("python tracebacker for worker %d available on %s\n", uwsgi.mywid, sock_path);

	for(;;) {
		UWSGI_RELEASE_GIL;
		int client_fd = accept(fd, (struct sockaddr *) &so_sun, &so_sun_len);
		if (client_fd < 0) {
			uwsgi_error("accept()");
			UWSGI_GET_GIL;
			continue;
		}
		UWSGI_GET_GIL;
// here is the core of the tracebacker
		PyObject *current_frames = PyEval_CallObject(_current_frames, (PyObject *)NULL);
		if (!current_frames) goto end2;

		PyObject *current_frames_items = PyObject_GetAttrString(current_frames, "items");
		if (!current_frames_items) goto end;

		PyObject *frames_ret = PyEval_CallObject(current_frames_items, (PyObject *)NULL);
		if (!frames_ret) goto end3;

		PyObject *frames_iter = PyObject_GetIter(frames_ret);
		if (!frames_iter) goto end4;


		// we have the first frame, lets parse it
		if (write(client_fd, "*** uWSGI Python tracebacker output ***\n\n", 41) < 0) {
			uwsgi_error("write()");
		}
		PyObject *frame = PyIter_Next(frames_iter);
		while(frame) {
			PyObject *thread_id = PyTuple_GetItem(frame, 0);
			if (!thread_id) goto next2;

			PyObject *stack = PyTuple_GetItem(frame, 1);
			if (!stack) goto next2;

			PyObject *arg_tuple = PyTuple_New(1);
			PyTuple_SetItem(arg_tuple, 0, stack);
			Py_INCREF(stack);
			PyObject *stacktrace = PyEval_CallObject( extract_stack, arg_tuple);
			Py_DECREF(arg_tuple);
			if (!stacktrace) goto next2;
			
			PyObject *stacktrace_iter = PyObject_GetIter(stacktrace);
			if (!stacktrace_iter) { Py_DECREF(stacktrace); goto next2;}

			PyObject *st_items = PyIter_Next(stacktrace_iter);
			// we have the first traceback item
			while(st_items) {
#ifdef PYTHREE
				int thread_name_need_free = 0;
#endif
				PyObject *st_filename = PyTuple_GetItem(st_items, 0);
				if (!st_filename) { Py_DECREF(st_items); goto next; }
				PyObject *st_lineno = PyTuple_GetItem(st_items, 1);
				if (!st_lineno) {Py_DECREF(st_items); goto next;}
				PyObject *st_name = PyTuple_GetItem(st_items, 2);
				if (!st_name) {Py_DECREF(st_items); goto next;}

				PyObject *st_line = PyTuple_GetItem(st_items, 3);
//.........这里部分代码省略.........
开发者ID:Algy,项目名称:uwsgi,代码行数:101,代码来源:tracebacker.c


示例5: call_python_function

static LIST*
call_python_function(RULE* r, FRAME* frame)
{
    LIST* result = 0;
    PyObject* arguments = PyTuple_New(frame->args->count);
    int i ;
    PyObject* py_result;

    for(i = 0; i < frame->args->count; ++i)
    {
        PyObject* arg = PyList_New(0);
        LIST* l = lol_get( frame->args, i);

        for(; l; l = l->next)
        {
            PyObject* v = PyString_FromString(l->string);
            /* Steals reference to 'v' */
            PyList_Append(arg, v);            
        }
        /* Steals reference to 'arg' */
        PyTuple_SetItem(arguments, i, arg);
    }

    py_result = PyObject_CallObject(r->python_function, arguments);
    Py_DECREF(arguments);
    if (py_result != NULL) {
        
        if (PyList_Check(py_result)) {
            int size = PyList_Size(py_result);
            int i;
            for(i = 0; i < size; ++i)
            {
                PyObject* item = PyList_GetItem(py_result, i);
                if (PyString_Check(item))
                {
                    result = list_new(result, 
                                      newstr(PyString_AsString(item)));
                }
                else
                {
                    fprintf(stderr, "Non-string object returned by Python call\n");
                }
            }
        }
        else if (PyInstance_Check(py_result))
        {
            static char instance_name[1000];
            static char imported_method_name[1000];
            module_t* m;
            PyObject* method;
            PyObject* method_name = PyString_FromString("foo");
            RULE* r;

            fprintf(stderr, "Got instance!\n");

            snprintf(instance_name, 1000,
                     "pyinstance%d", python_instance_number);
            snprintf(imported_method_name, 1000,
                     "pyinstance%d.foo", python_instance_number);
            ++python_instance_number;
            
            m = bindmodule(instance_name);

            /* This is expected to get bound method. */
            method = PyObject_GetAttr(py_result, method_name);
            
            r = bindrule( imported_method_name, root_module() );

            r->python_function = method;

            result = list_new(0, newstr(instance_name));    

            Py_DECREF(method_name);
        }
        else if (py_result == Py_None)
        {
            result = L0;
        }
        else
        {
            fprintf(stderr, "Non-list object returned by Python call\n");
        }

        Py_DECREF(py_result);
    }
    else {
        PyErr_Print();
        fprintf(stderr,"Call failed\n");
    }
    
    return result;
}
开发者ID:Albermg7,项目名称:boost,代码行数:92,代码来源:compile.c


示例6: uwsgi_log

PyObject *uwsgi_paste_loader(void *arg1) {

    char *paste = (char *) arg1;
    PyObject *paste_module, *paste_dict, *paste_loadapp;
    PyObject *paste_arg, *paste_app;

    uwsgi_log( "Loading paste environment: %s\n", paste);

    if (up.paste_logger) {
        PyObject *paste_logger_dict = get_uwsgi_pydict("paste.script.util.logging_config");
        if (paste_logger_dict) {
            PyObject *paste_logger_fileConfig = PyDict_GetItemString(paste_logger_dict, "fileConfig");
            if (paste_logger_fileConfig) {
                PyObject *paste_logger_arg = PyTuple_New(1);
                if (!paste_logger_arg) {
                    PyErr_Print();
                    exit(UWSGI_FAILED_APP_CODE);
                }
                PyTuple_SetItem(paste_logger_arg, 0, UWSGI_PYFROMSTRING(paste+7));
                if (python_call(paste_logger_fileConfig, paste_logger_arg, 0, NULL)) {
                    PyErr_Print();
                }
            }
        }
    }

    paste_module = PyImport_ImportModule("paste.deploy");
    if (!paste_module) {
        PyErr_Print();
        exit(UWSGI_FAILED_APP_CODE);
    }

    paste_dict = PyModule_GetDict(paste_module);
    if (!paste_dict) {
        PyErr_Print();
        exit(UWSGI_FAILED_APP_CODE);
    }

    paste_loadapp = PyDict_GetItemString(paste_dict, "loadapp");
    if (!paste_loadapp) {
        PyErr_Print();
        exit(UWSGI_FAILED_APP_CODE);
    }

    paste_arg = PyTuple_New(1);
    if (!paste_arg) {
        PyErr_Print();
        exit(UWSGI_FAILED_APP_CODE);
    }

    if (PyTuple_SetItem(paste_arg, 0, UWSGI_PYFROMSTRING(paste))) {
        PyErr_Print();
        exit(UWSGI_FAILED_APP_CODE);
    }

    paste_app = PyEval_CallObject(paste_loadapp, paste_arg);
    if (!paste_app) {
        PyErr_Print();
        exit(UWSGI_FAILED_APP_CODE);
    }


    return paste_app;
}
开发者ID:rascalmicro,项目名称:uwsgi,代码行数:64,代码来源:pyloader.c


示例7: AerospikeClient_GetNodes_Returnlist

/**
 ******************************************************************************************************
 * Iterates over the hosts in the cluster and creates the list to be returned to the python client.
 *
 * @param err                   as_error object
 * @param command               Request string sent from the python client
 * @param nodes_tuple           List containing details of each host
 * @param return_value          List t o be returned back to the python client
 * @param host_index            Index of the list nodes_tuple
 * @param index                 Index of the list to be returned.
 *
 * Returns information about a host.
 ********************************************************************************************************/
static PyObject * AerospikeClient_GetNodes_Returnlist(as_error* err,
	PyObject * command, PyObject * nodes_tuple[], PyObject * return_value,
	uint32_t host_index, Py_ssize_t index) {

	char* tok = NULL;
	char* saved = NULL;
	PyObject * value_tok = NULL;
	bool break_flag = false;

	tok = strtok_r(PyStr_AsString(command), INFO_REQUEST_RESPONSE_DELIMITER, &saved);
	if (tok == NULL) {
		as_error_update(err, AEROSPIKE_ERR_CLIENT, "Unable to get addr in service");
		goto CLEANUP;
	}
	while (tok != NULL && (host_index < MAX_HOST_COUNT)) {
		tok = strtok_r(NULL, IP_PORT_DELIMITER, &saved);
#if defined(__APPLE__)
		if (tok == NULL || saved == NULL) {
#else
		if (tok == NULL || *saved == '\0') {
#endif
			goto CLEANUP;
		}

		nodes_tuple[host_index] = PyTuple_New(2);

		value_tok = PyStr_FromString(tok);
		PyTuple_SetItem(nodes_tuple[host_index], 0 , value_tok);
		//Py_DECREF(value_tok);

		if(strcmp(PyStr_AsString(command),"response_services_p")) {
			tok = strtok_r(NULL, HOST_DELIMITER, &saved);
			if (tok == NULL) {
				as_error_update(err, AEROSPIKE_ERR_CLIENT, "Unable to get port");
				goto CLEANUP;
			}

			if (strstr(tok, INFO_RESPONSE_END)) {
				tok = strtok_r(tok, INFO_RESPONSE_END, &saved);
				break_flag = true;
			}
		} else {
			tok = strtok_r(NULL, INFO_RESPONSE_END, &saved);
			if (tok == NULL) {
				as_error_update(err, AEROSPIKE_ERR_CLIENT, "Unable to get port in service");
				goto CLEANUP;
			}
		}

		value_tok = PyInt_FromString(tok, NULL, 10);
		PyTuple_SetItem(nodes_tuple[host_index], 1 , value_tok);
		PyList_Insert(return_value, index , nodes_tuple[host_index]);
		Py_DECREF(nodes_tuple[host_index]);
		index++;
		host_index++;

		if (break_flag == true) {
			goto CLEANUP;
		}

	}
CLEANUP:

	if ( err->code != AEROSPIKE_OK ) {
		PyObject * py_err = NULL;
		error_to_pyobject(err, &py_err);
		PyObject *exception_type = raise_exception(err);
		PyErr_SetObject(exception_type, py_err);
		Py_DECREF(py_err);
		return NULL;
	}
	return return_value;
}
/**
 ******************************************************************************************************
 * Returns data about the nodes to AerospikeClient_GetNodes.
 *
 * @param self                  AerospikeClient object
 *
 * Returns a list containing the details of the nodes.
 ********************************************************************************************************/
static PyObject * AerospikeClient_GetNodes_Invoke(
	AerospikeClient * self) {

	PyObject * response_services_p = NULL;
	PyObject * response_service_p = NULL;
	PyObject * nodes_tuple[MAX_HOST_COUNT] = {0};
//.........这里部分代码省略.........
开发者ID:Fabma,项目名称:aerospike-client-python,代码行数:101,代码来源:info_node.c


示例8: coordinator_convert


//.........这里部分代码省略.........
        view_height = fabs(extent[1] - extent[3]);
    
        if ((double)(pixel_width)/(double)(pixel_height) < view_width/view_height)
        {
            ratioX = pixel_width/view_width;
            ratioY = ratioX;
            startY = (int)((pixel_height-view_height*ratioY)/2.0);
        }
        else
        {
            ratioY = pixel_height/view_height;
            ratioX = ratioY;
            startX = (int)((pixel_width-view_width*ratioX)/2.0);
        }
    
        margin_x = (int)(pixel_width * (1-scaleX) / 2.0); 
        margin_y = (int)(pixel_height* (1-scaleY) / 2.0); 
    }
    
    // converter coordinators
    PyObject * objects = PyDict_GetItemString(map_dict, shape_name); 
    
    if (objects == NULL)
        return PyList_New(0);
   
    PyObject * list = NULL, * parts = NULL, * point = NULL;
    PyObject *vertices = NULL, *px = NULL, *py =NULL;
    PyObject *_point=NULL,*_px=NULL,*_py=NULL;
    PyObject *polygon=NULL,*part = NULL;

    list = PyList_New(nEntities);
    
    for (i=0; i< nEntities; i++)
    {   
        if (nShapeType == SHPT_POINT || nShapeType == SHPT_POINTZ)
        {
            _point = PyList_GetItem(objects, i);            
            _px = PyTuple_GetItem(_point, 0); 
            _py = PyTuple_GetItem(_point, 1); 
           
            x = PyFloat_AsDouble(_px); 
            y = PyFloat_AsDouble(_py); 
       
            tmp_px = pan_offset_x + startX + ratioX * (x - extent[0]);
            tmp_px = round(offset_x + tmp_px * scaleX + margin_x);
            
            tmp_py = pixel_height - pan_offset_y - startY - ratioY * (y-extent[1]);
            tmp_py = round(offset_y + tmp_py * scaleY + margin_y);

            px = PyInt_FromLong((int)tmp_px);
            py = PyInt_FromLong((int)tmp_py);
            point = PyTuple_New(2);
            
            PyTuple_SetItem(point, 0, px);
            PyTuple_SetItem(point, 1, py);
                
            PyList_SetItem(list, i, point);
        }
        else if (nShapeType == SHPT_POLYGON || nShapeType == SHPT_POLYGONZ)
        {  
            polygon = PyList_GetItem(objects, i);
            nParts = (int)PyList_Size(polygon);
            
            parts = PyList_New(nParts);
            
            for (j=0; j < nParts; j++)
            { 
                part = PyList_GetItem(polygon, j);
                numPoints = (int)PyList_Size(part);
                
                vertices = PyTuple_New(numPoints);
                for (k=0; k < numPoints; k++)
                {
                    _point = PyList_GetItem(part, k);
                    _px = PyTuple_GetItem(_point, 0); 
                    _py = PyTuple_GetItem(_point, 1); 
                    
                    x = PyFloat_AsDouble(_px); 
                    y = PyFloat_AsDouble(_py); 
           
                    tmp_px = pan_offset_x + startX + ratioX * (x - extent[0]);
                    tmp_px = offset_x + tmp_px * scaleX + margin_x;
            
                    tmp_py = pixel_height - pan_offset_y - startY - ratioY * (y-extent[1]);
                    tmp_py = offset_y + tmp_py * scaleY + margin_y;

                    px = PyInt_FromLong((int)tmp_px);
                    py = PyInt_FromLong((int)tmp_py);
                    point = PyTuple_New(2);
                    PyTuple_SetItem(point, 0, px);
                    PyTuple_SetItem(point, 1, py);
                    PyTuple_SetItem(vertices, k, point);
                }
                PyList_SetItem(parts,j,vertices);
            }   
            PyList_SetItem(list, i, parts);
        }
    }    
    return list;
}
开发者ID:GeoDaCenter,项目名称:CAST,代码行数:101,代码来源:coordinator_converter.c


示例9: read_centroids

static PyObject *
read_centroids(PyObject * self, PyObject * args)
{
    SHPHandle hSHP;
    PyObject * cobject;

    if (!PyArg_ParseTuple(args, "O!", &PyCObject_Type, &cobject))
        return NULL;

    hSHP = PyCObject_AsVoidPtr(cobject);
    
    int nEntities;
    int nShapeType;

    SHPGetInfo(hSHP, &nEntities, &nShapeType, NULL, NULL);
    PyObject * list = NULL, * parts = NULL, * point = NULL, *px = NULL, *py = NULL;

    SHPObject * psCShape;
    int i,j,count;
    double x,y;

    list = PyList_New(nEntities);
   
    for (i=0; i< nEntities; i++)
    {   
        psCShape = SHPReadObject( hSHP, i);   
    
        if (psCShape->nSHPType == SHPT_POINT || psCShape->nSHPType == SHPT_POINTZ)
        {
            /*
            x = psCShape->centroidXX[0];
            y = psCShape->centroidYY[0];
            point = Py_BuildValue("(dd)", x,y);
            PyList_SetItem(list, i, point);
            */
            return PyList_New(0);
        }
        else if (psCShape->nSHPType == SHPT_POLYGON || psCShape->nSHPType == SHPT_POLYGONZ)
        {   
            // read polygons from shp file
            count = psCShape->nParts > 1 ? psCShape->nParts : 1;
            parts = PyList_New(count);

            for (j=0; j <psCShape->nParts; j++)
            { 
                x = psCShape->centroidXX[j];
                y = psCShape->centroidYY[j];
                
                //point = Py_BuildValue("(dd)", x,y);
                px = PyFloat_FromDouble(x);
                py = PyFloat_FromDouble(y);
                point = PyTuple_New(2);
                PyTuple_SetItem(point, 0, px);
                PyTuple_SetItem(point, 1, py);
                
                PyList_SetItem(parts,j,point);
            }   
            PyList_SetItem(list, i, parts);
        }
        SHPDestroyObject(psCShape);
    }    
    return list;
}
开发者ID:GeoDaCenter,项目名称:CAST,代码行数:63,代码来源:coordinator_converter.c


示例10: embed_sim_init


//.........这里部分代码省略.........
    simlog_func = PyObject_GetAttrString(simlog_obj, "_willLog");
    if (simlog_func == NULL) {
        PyErr_Print();
        fprintf(stderr, "Failed to get the _willLog method");
        goto cleanup;
    }

    if (!PyCallable_Check(simlog_func)) {
        PyErr_Print();
        fprintf(stderr, "_willLog is not callable");
        goto cleanup;
    }

    set_log_filter(simlog_func);

    argv_list = PyList_New(0);
    for (i = 0; i < info->argc; i++) {
        arg_value = PyString_FromString(info->argv[i]);
        PyList_Append(argv_list, arg_value);
    }

    arg_dict = PyModule_GetDict(cocotb_module);
    PyDict_SetItemString(arg_dict, "argv", argv_list);

    argc = PyInt_FromLong(info->argc);
    PyDict_SetItemString(arg_dict, "argc", argc);

    if (!PyCallable_Check(simlog_func)) {
        PyErr_Print();
        fprintf(stderr, "_printRecord is not callable");
        goto cleanup;
    }

    gpi_print_registered_impl();
    LOG_INFO("Running on %s version %s", info->product, info->version);
    LOG_INFO("Python interpreter initialised and cocotb loaded!");

    // Now that logging has been set up ok we initialise the testbench
    if (-1 == PyObject_SetAttrString(cocotb_module, "SIM_NAME", PyString_FromString(info->product))) {
        PyErr_Print();
        fprintf(stderr, "Unable to set SIM_NAME");
        goto cleanup;
    }

    // Set languare in use
    const char *lang = getenv("TOPLEVEL_LANG");
    if (!lang)
       fprintf(stderr, "You should really set TOPLEVEL_LANG to \"verilog/vhdl\"");
    else {
        if (-1 == PyObject_SetAttrString(cocotb_module, "LANGUAGE", PyString_FromString(lang))) {
            fprintf(stderr, "Unable to set LANGUAGE");
            goto cleanup;
        }
    }

    // Hold onto a reference to our _fail_test function
    pEventFn = PyObject_GetAttrString(cocotb_module, "_sim_event");

    if (!PyCallable_Check(pEventFn)) {
        PyErr_Print();
        fprintf(stderr, "cocotb._sim_event is not callable");
        goto cleanup;
    }
    Py_INCREF(pEventFn);

    cocotb_init = PyObject_GetAttrString(cocotb_module, "_initialise_testbench");         // New reference

    if (cocotb_init == NULL || !PyCallable_Check(cocotb_init)) {
        if (PyErr_Occurred())
            PyErr_Print();
        fprintf(stderr, "Cannot find function \"%s\"\n", "_initialise_testbench");
        Py_DECREF(cocotb_init);
        goto cleanup;
    }

    cocotb_args = PyTuple_New(1);
    PyTuple_SetItem(cocotb_args, 0, PyLong_FromLong((long)dut));        // Note: This function “steals” a reference to o.
    cocotb_retval = PyObject_CallObject(cocotb_init, cocotb_args);

    if (cocotb_retval != NULL) {
        LOG_DEBUG("_initialise_testbench successful");
        Py_DECREF(cocotb_retval);
    } else {
        PyErr_Print();
        fprintf(stderr,"Call failed\n");
        gpi_sim_end();
        goto cleanup;
    }

    FEXIT

cleanup:
    if (cocotb_module) {
        Py_DECREF(cocotb_module);
    }
    if (arg_dict) {
        Py_DECREF(arg_dict);
    }
    PyGILState_Release(gstate);
}
开发者ID:scottwilson46,项目名称:cocotb,代码行数:101,代码来源:gpi_embed.c


示例11: _adjust_players

static PyObject* _adjust_players(PyObject* self, PyObject* args) {
	PyObject* list_obj;
	PyObject* seq;
	int size, i = 0;

	// get the list from the arguments
	// note: "O" flag means it's a python object
	if (!PyArg_ParseTuple(args, "O", &list_obj)) {
		return NULL;
	}

	// verify that it's actually a list
	seq = PySequence_Fast(list_obj, "expected a list");
	if (!seq) {
		return NULL;
	}

	// get the list size
	size = PySequence_Size(seq);
	if (size < 0) {
		return NULL;
	}

	// create a vector of players to hold our soon-to-be-created player objects
	std::vector<Player*> players;
	PyObject* py_tuple;
	for (i = 0; i < size; ++i) {
		// create a new player object
		Player* p = new Player();

		// get the current item from the list, which happens to be a tuple (mu, sigma, rank)
		py_tuple = PySequence_Fast_GET_ITEM(seq, i);


		// convert the tuple items into their c types
		p->mu = PyFloat_AsDouble(PyTuple_GetItem(py_tuple, 0));
		p->sigma = PyFloat_AsDouble(PyTuple_GetItem(py_tuple, 1));
		p->rank = (int)PyInt_AsLong(PyTuple_GetItem(py_tuple, 2));

		// add the player to the players vector
		players.push_back(p);
	}

	// run trueskill on the players
	TrueSkill ts;
	ts.adjust_players(players);

	// create the result list
	PyObject* result = PyList_New(size);
	for (i = 0; i < size; ++i) {
		// create a tuple and set it's values for the player
		PyObject* py_tuple;

		py_tuple = PyTuple_New(3);
		PyTuple_SetItem(py_tuple, 0, PyFloat_FromDouble(players[i]->mu));
		PyTuple_SetItem(py_tuple, 1, PyFloat_FromDouble(players[i]->sigma));
		PyTuple_SetItem(py_tuple, 2, PyInt_FromLong((long)players[i]->rank));

		// push the tuple onto the list
		PyList_SetItem(result, i, py_tuple);
	}

	// return the list
	return result;
}
开发者ID:JesseBuesking,项目名称:trueskill,代码行数:65,代码来源:python_wrapper.cpp


示例12: RtAudio_getDeviceInfo

static PyObject *
RtAudio_getDeviceInfo(PyRtAudio *self, PyObject *args)
{
  int device;
  RtAudioDeviceInfo info;

  PyObject *name = NULL;
  PyObject *probed = NULL;
  PyObject *outputChannels = NULL;
  PyObject *inputChannels = NULL;
  PyObject *duplexChannels = NULL;
  PyObject *isDefault = NULL;
  PyObject *sampleRates = NULL;
  PyObject *nativeFormats = NULL;
  PyObject *deviceInfo = NULL;


  if(!PyArg_ParseTuple(args, "i", &device))
    return NULL;

  try
    {
      info = self->rtaudio->getDeviceInfo(device);
    }
  catch(RtError &error)
    {
      PyErr_Format(RtAudioError, error.getMessageString());
      return NULL;
    }

  name = PyString_FromString(info.name.c_str());
  if(name == NULL) return NULL;
  
  if(info.probed)
    {
      probed = Py_True;
      Py_INCREF(Py_True);
    }
  else
    {
      probed = Py_False;
      Py_INCREF(Py_False);
    }
  
  outputChannels = PyInt_FromLong(info.outputChannels);
  if(outputChannels == NULL) goto fail;
  
  inputChannels = PyInt_FromLong(info.inputChannels);
  if(inputChannels == NULL) goto fail;
  
  duplexChannels = PyInt_FromLong(info.duplexChannels);
  if(duplexChannels == NULL) goto fail;
  
  if(info.isDefault)
    {
      isDefault = Py_True;
      Py_INCREF(Py_True);
    }
  else
    {
      isDefault = Py_False;
      Py_INCREF(Py_False);
    }
  
  sampleRates = PyTuple_New(info.sampleRates.size());
  if(sampleRates == NULL)
    goto fail;

  for(uint i=0; i < info.sampleRates.size(); i++)
    {
      PyObject *rate = PyInt_FromLong(info.sampleRates[i]);
      if(rate == NULL)
        goto fail;
      if(PyTuple_SetItem(sampleRates, i, rate))
        {
          Py_DECREF(rate);
          goto fail;
        }
    }

  nativeFormats = PyLong_FromUnsignedLong(info.nativeFormats);
  if(nativeFormats == NULL)
    return NULL;
  
  deviceInfo = PyDict_New();
  if(deviceInfo == NULL)
    goto fail;

  if(PyDict_SetItemString(deviceInfo, "name", name))
    goto fail;
  if(PyDict_SetItemString(deviceInfo, "probed", probed))
    goto fail;
  if(PyDict_SetItemString(deviceInfo, "outputChannels", outputChannels))
    goto fail;
  if(PyDict_SetItemString(deviceInfo, "inputChannels", inputChannels)) 
    goto fail;
  if(PyDict_SetItemString(deviceInfo, "deviceChannels", duplexChannels))
    goto fail;
  if(PyDict_SetItemString(deviceInfo, "isDefault", isDefault))
    goto fail;
//.........这里部分代码省略.........
开发者ID:RikVerschueren,项目名称:AccordionMega,代码行数:101,代码来源:rtaudiomodule.cpp


示例13: ot_pvw_receive

PyObject *
ot_pvw_receive(PyObject *self, PyObject *args)
{
    PyObject *py_state, *py_choices, *py_return = NULL;
    struct dm_ddh_crs crs;
    struct dm_ddh_pk pk;
    struct ddh_sk sk;
    struct ddh_ctxt ctxt;
    struct state *st;
    int num_ots;
    unsigned int N, msglength, err = 0;
    double start, end;

    if (!PyArg_ParseTuple(args, "OOII", &py_state, &py_choices, &N, &msglength))
        return NULL;

    st = (struct state *) PyCapsule_GetPointer(py_state, NULL);
    if (st == NULL)
        return NULL;

    if (N != 2) {
        PyErr_SetString(PyExc_RuntimeError, "N must be 2");
        return NULL;
    }

    if ((num_ots = PySequence_Length(py_choices)) == -1)
        return NULL;

    start = current_time();
    // FIXME: choice of mode should not be hardcoded
    dm_ddh_crs_setup(&crs, EXT, &st->p);
    end = current_time();
    fprintf(stderr, "CRS setup: %f\n", end - start);

    dm_ddh_pk_setup(&pk);
    ddh_sk_setup(&sk);
    ddh_ctxt_setup(&ctxt);

    py_return = PyTuple_New(num_ots);

    start = current_time();
    for (int j = 0; j < num_ots; ++j) {
        unsigned int choice;
        // double start, end;

        choice = PyLong_AsLong(PySequence_GetItem(py_choices, j));

        // start = current_time();
        dm_ddh_keygen(&pk, &sk, choice, &crs, &st->p);
        // end = current_time();
        // fprintf(stderr, "ddh keygen: %f\n", end - start);

        // start = current_time();
        send_dm_ddh_pk(&pk, st);
        // end = current_time();
        // fprintf(stderr, "send dm ddh pk: %f\n", end - start);

        for (unsigned int b = 0; b <= 1; ++b) {
            char *msg;
            PyObject *str;

            // start = current_time();
            receive_ddh_ctxt(&ctxt, st);
            // end = current_time();
            // fprintf(stderr, "receive dm ddh ctxt: %f\n", end - start);

            // start = current_time();
            msg = dm_ddh_dec(&sk, &ctxt, &st->p);
            // end = current_time();
            // fprintf(stderr, "decrypt ddh ctxt: %f\n", end - start);

            str = PyString_FromStringAndSize(msg, msglength);
            free(msg);
            if (str == NULL) {
                err = 1;
                goto cleanup;
            }
            if (choice == b) {
                PyTuple_SetItem(py_return, j, str);
            }
        }
    }
    end = current_time();
    fprintf(stderr, "OT: %f\n", end - start);

 cleanup:
    ddh_ctxt_cleanup(&ctxt);
    ddh_sk_cleanup(&sk);
    dm_ddh_pk_cleanup(&pk);
    dm_ddh_crs_cleanup(&crs);

    if (err)
        return NULL;
    else
        return py_return;
}
开发者ID:amaloz,项目名称:otlib,代码行数:96,代码来源:ot_pvw.cpp


示例14: python_orbclients

static PyObject *
python_orbclients( PyObject *self, PyObject *args ) {
	char	*usage = "Usage: _orbclients(orb)\n";
	int	orbfd;
	Orbclient *oc = 0;
	double 	atime;
	int	nclients;
	int	iclient;
	int	rc;
	char	*ip;
	struct	in_addr addr;
	PyObject *obj;
	PyObject *client_obj;

	if( ! PyArg_ParseTuple( args, "i", &orbfd ) ) {

		if( ! PyErr_Occurred() ) {

			PyErr_SetString( PyExc_RuntimeError, usage );
		}

		return NULL;
	}

	rc = orbclients( orbfd, &atime, &oc, &nclients );

	if( rc < 0 ) {

		PyErr_SetString( PyExc_RuntimeError, "error querying orb clients" );

		return NULL;
	}

	obj = PyTuple_New( nclients );

	for( iclient = 0; iclient < nclients; iclient++ ) {

		memcpy( &addr.s_addr, oc[iclient].address, 4 );
		ip = inet_ntoa( addr );

		client_obj = PyDict_New();

		PyDict_SetItemString( client_obj, "lastpkt", Py_BuildValue( "f", oc[iclient].lastpkt ) );
		PyDict_SetItemString( client_obj, "started", Py_BuildValue( "f", oc[iclient].started ) );
		PyDict_SetItemString( client_obj, "read", PyInt_FromLong( (long) oc[iclient].read ) );
		PyDict_SetItemString( client_obj, "pid", Py_BuildValue( "i", oc[iclient].pid ) );
		PyDict_SetItemString( client_obj, "bytes", PyInt_FromLong( (long) oc[iclient].bytes ) );
		PyDict_SetItemString( client_obj, "packets", PyInt_FromLong( (long) oc[iclient].packets ) );
		PyDict_SetItemString( client_obj, "pktid", Py_BuildValue( "i", oc[iclient].pktid ) );
		PyDict_SetItemString( client_obj, "port", Py_BuildValue( "i", oc[iclient].port ) );
		PyDict_SetItemString( client_obj, "address", Py_BuildValue( "s", ip ) );
		PyDict_SetItemString( client_obj, "thread", Py_BuildValue( "i", oc[iclient].thread ) );
		PyDict_SetItemString( client_obj, "fd", Py_BuildValue( "i", oc[iclient].fd ) );
		PyDict_SetItemString( client_obj, "nreject", Py_BuildValue( "i", oc[iclient].nreject ) );
		PyDict_SetItemString( client_obj, "nselect", Py_BuildValue( "i", oc[iclient].nselect ) );
		PyDict_SetItemString( client_obj, "errors", Py_BuildValue( "i", oc[iclient].errors ) );
		PyDict_SetItemString( client_obj, "priority", Py_BuildValue( "i", oc[iclient].priority ) );
		PyDict_SetItemString( client_obj, "lastrequest", Py_BuildValue( "i", oc[iclient].lastrequest ) );
		PyDict_SetItemString( client_obj, "mymessages", Py_BuildValue( "i", oc[iclient].mymessages ) );
		PyDict_SetItemString( client_obj, "nrequests", PyInt_FromLong( (long) oc[iclient].nrequests ) );
		PyDict_SetItemString( client_obj, "nwrites", PyInt_FromLong( (long) oc[iclient].nwrites ) );
		PyDict_SetItemString( client_obj, "nreads", PyInt_FromLong( (long) oc[iclient].nreads ) );
		PyDict_SetItemString( client_obj, "written", PyInt_FromLong( (long) oc[iclient].written ) );
		PyDict_SetItemString( client_obj, "perm", PyString_FromFormat( "%c", oc[iclient].perm ) );
		PyDict_SetItemString( client_obj, "what", Py_BuildValue( "s", oc[iclient].what ) );
		PyDict_SetItemString( client_obj, "host", Py_BuildValue( "s", oc[iclient].host ) );
		PyDict_SetItemString( client_obj, "who", Py_BuildValue( "s", oc[iclient].who ) );
		PyDict_SetItemString( client_obj, "select", Py_BuildValue( "s", oc[iclient].select ) );
		PyDict_SetItemString( client_obj, "reject", Py_BuildValue( "s", oc[iclient].reject ) );

		PyTuple_SetItem( obj, iclient, client_obj );
	}

	return Py_BuildValue( "fO", atime, obj );
}
开发者ID:vonseg,项目名称:antelope_contrib,代码行数:75,代码来源:_orb.c


示例15: main

int main(int argc, char** argv)
{
    // 初始化Python
    //在使用Python系统前,必须使用Py_Initialize对其
    //进行初始化。它会载入Python的内建模块并添加系统路
    //径到模块搜索路径中。这个函数没有返回值,检查系统
    //是否初始化成功需要使用Py_IsInitialized。

    Py_Initialize();

    // 检查初始化是否成功
    if ( !Py_IsInitialized() )
    {
        return -1;
    }

    // 添加当前路径
    //把输入的字符串作为Python代码直接运行,返回0
    //表示成功,-1表示有错。大多时候错误都是因为字符串
    //中有语法错误。
    PyRun_SimpleString("import sys");
    PyRun_SimpleString("sys.path.append('./')");
    PyObject *pName,*pModule,*pDict,*pFunc,*pArgs;

    // 载入名为pytest的脚本
    pName = PyString_FromString("pytest");
    pModule = PyImport_Import(pName);
    if ( !pModule )
    {
        printf("can't find pytest.py");
        getchar();
        return -1;
    }
    pDict = PyModule_GetDict(pModule);
    if ( !pDict )
    {
        return -1;
    }

    // 找出函数名为add的函数
    pFunc = PyDict_GetItemString(pDict, "add");
    if ( !pFunc || !PyCallable_Check(pFunc) )
    {
        printf("can't find function [add]");
        getchar();
        return -1;
    }

    // 参数进栈
    *pArgs;
    pArgs = PyTuple_New(2);

    //  PyObject* Py_BuildValue(char *format, ...)
    //  把C++的变量转换成一个Python对象。当需要从
    //  C++传递变量到Python时,就会使用这个函数。此函数
    //  有点类似C的printf,但格式不同。常用的格式有
    //  s 表示字符串,
    //  i 表示整型变量,
    //  f 表示浮点数,
    //  O 表示一个Python对象。

    PyTuple_SetItem(pArgs, 0, Py_BuildValue("l",3));
    PyTuple_SetItem(pArgs, 1, Py_BuildValue("l",4));

    // 调用Python函数
    PyObject_CallObject(pFunc, pArgs);

    //下面这段是查找函数foo 并执行foo
    pFunc = PyDict_GetItemString(pDict, "foo");
    if ( !pFunc || !PyCallable_Check(pFunc) )
    {
        printf("can't find function [foo]");
        getchar();
        return -1;
    }

    pArgs = PyTuple_New(1);
    PyTuple_SetItem(pArgs, 0, Py_BuildValue("l",2)); //

    PyObject_CallObject(pFunc, pArgs);


    Py_DECREF(pName);
    Py_DECREF(pArgs);
    Py_DECREF(pModule);

    // 关闭Python
    Py_Finalize();
    return 0;
} 
开发者ID:feixiaoxing,项目名称:python,代码行数:90,代码来源:python.cpp


示例16: read_objects


鲜花

握手

雷人

路过

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

请发表评论

全部评论

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

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

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

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

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