Exemplo n.º 1
0
int main() {
	Py_Initialize();
	if (!Py_IsInitialized())
		return -1;
	PyRun_SimpleString("import sys");
	PyRun_SimpleString("sys.path.append('./')");
	//导入模块
	PyObject* pModule = PyImport_ImportModule("testpy");
	if (!pModule) {
		printf("Cant open python file!/n");
		return -1;
	}
	//模块的字典列表
	PyObject* pDict = PyModule_GetDict(pModule);
	if (!pDict) {
		printf("Cant find dictionary./n");
		return -1;
	}
	//打印出来看一下
	printDict(pDict);
	//演示函数调用
	PyObject* pFunHi = PyDict_GetItemString(pDict, "sayhi");
	PyObject_CallFunction(pFunHi, "s", "lhb");
	Py_DECREF(pFunHi);
	//演示构造一个Python对象,并调用Class的方法
	//获取Second类
	PyObject* pClassSecond = PyDict_GetItemString(pDict, "Second");
	if (!pClassSecond) {
		printf("Cant find second class./n");
		return -1;
	}
	//获取Person类
	PyObject* pClassPerson = PyDict_GetItemString(pDict, "Person");
	if (!pClassPerson) {
		printf("Cant find person class./n");
		return -1;
	}
	//构造Second的实例
	PyObject* pInstanceSecond = PyInstance_New(pClassSecond, NULL, NULL);
	if (!pInstanceSecond) {
		printf("Cant create second instance./n");
		return -1;
	}
	//构造Person的实例
	PyObject* pInstancePerson = PyInstance_New(pClassPerson, NULL, NULL);
	if (!pInstancePerson) {
		printf("Cant find person instance./n");
		return -1;
	}
	//把person实例传入second的invoke方法
	PyObject_CallMethod(pInstanceSecond, "invoke", "O", pInstancePerson);
	//释放
	Py_DECREF(pInstanceSecond);
	Py_DECREF(pInstancePerson);
	Py_DECREF(pClassSecond);
	Py_DECREF(pClassPerson);
	Py_DECREF(pModule);
	Py_Finalize();
	return 0;
}
Exemplo n.º 2
0
Arquivo: cpp.cpp Projeto: hpzhong/tyd
int main() {  
	Py_Initialize();  
	if (!Py_IsInitialized())  
		return -1;  
	PyRun_SimpleString("import sys");  
	PyRun_SimpleString("sys.path.append('./')");  

	PyObject* pModule = PyImport_ImportModule("testpy");  
	if (!pModule) {  
		printf("Cant open python file!\n");  
		return -1;  
	}  

	PyObject* pDict = PyModule_GetDict(pModule);  
	if (!pDict) {  
		printf("Cant find dictionary.\n");  
		return -1;  
	}  
	
	printDict(pDict);  
	PyObject* pFunHi = PyDict_GetItemString(pDict, "sayhi");  
	PyObject_CallFunction(pFunHi, "s", "lhb");  
	Py_DECREF(pFunHi);  
	PyObject* pClassSecond = PyDict_GetItemString(pDict, "Second");  
	if (!pClassSecond) {  
		printf("Cant find second class.\n");  
		return -1;  
	}  

	PyObject* pClassPerson = PyDict_GetItemString(pDict, "Person");  
	if (!pClassPerson) {  
		printf("Cant find person class.\n");  
		return -1;  
	}  

	PyObject* pInstanceSecond = PyInstance_New(pClassSecond, NULL, NULL);  
	if (!pInstanceSecond) {  
		printf("Cant create second instance.\n");  
		return -1;  
	}  
	
	PyObject* pInstancePerson = PyInstance_New(pClassPerson, NULL, NULL);  
	if (!pInstancePerson) {  
		printf("Cant find person instance.\n");  
		return -1;  
	}  
	PyObject_CallMethod(pInstanceSecond, "invoke", "O", pInstancePerson);  
	
	Py_DECREF(pInstanceSecond);  
	Py_DECREF(pInstancePerson);  
	Py_DECREF(pClassSecond);  
	Py_DECREF(pClassPerson);  
	Py_DECREF(pModule);  
	Py_Finalize();  
	return 0;  
}  
Exemplo n.º 3
0
void set_mpx_exception(char *name, PyObject *args, PyObject *kw)
{
  PyObject *klass;
  PyObject *object;
  klass = PyObject_GetAttrString(exception_module, name);
  object = PyInstance_New(klass, args, kw);
  PyErr_SetObject(klass, object);
}
static char *hexin_http_scribe_init(ngx_conf_t *cf, ngx_command_t *cmd, void *conf)
{
	hexin_http_scribe_loc_conf_t *loc_conf = conf;
	hexin_http_scribe_python = ngx_palloc(cf->pool, sizeof(hexin_http_scribe_python_t));
		
	Py_Initialize();
	 // 检查初始化是否成功
	if (!Py_IsInitialized() ) {
		return NGX_CONF_ERROR;
	}
	
	PyRun_SimpleString("import sys");   
	PyRun_SimpleString((char*)loc_conf->scribe_python_workspace.data); 
	hexin_http_scribe_python->pModule = PyImport_ImportModule((char*)loc_conf->scribe_python_filename.data); 
	if (!hexin_http_scribe_python->pModule) {  
		printf("can't find ScribeClient.py");  
		getchar();
		return NGX_CONF_ERROR;  
	} 
	hexin_http_scribe_python->pDict = PyModule_GetDict(hexin_http_scribe_python->pModule);  
	if (!hexin_http_scribe_python->pDict) {
		return NGX_CONF_ERROR;  
	}  
	hexin_http_scribe_python->pScriberClientClass = PyDict_GetItemString(hexin_http_scribe_python->pDict, (char*)loc_conf->scribe_python_classname.data);
	if (!hexin_http_scribe_python->pScriberClientClass || !PyClass_Check(hexin_http_scribe_python->pScriberClientClass)) {
		return NGX_CONF_ERROR;  
	}

	PyObject *pArgs = PyTuple_New(3);
	PyTuple_SetItem(pArgs, 0, Py_BuildValue("s",loc_conf->scribe_host.data));
	PyTuple_SetItem(pArgs, 1, Py_BuildValue("s",loc_conf->scribe_port.data));
	PyTuple_SetItem(pArgs, 2, Py_BuildValue("b","False"));
	hexin_http_scribe_python->pScriberClient = PyInstance_New(hexin_http_scribe_python->pScriberClientClass, pArgs, NULL);
	 
	if (!hexin_http_scribe_python->pScriberClient) { 
		return NGX_CONF_ERROR;  
	}
	hexin_http_scribe_python->isinit = 1;
   
	ngx_http_complex_value_t  cv; 
    	ngx_memzero(&cv, sizeof(ngx_http_complex_value_t));
	cv.value.len = success_submit.len;
	cv.value.data = success_submit.data;
	hexin_http_scribe_python->success_response = cv;
	loc_conf->message_index = ngx_http_get_variable_index(cf, &message_flag);

	ngx_http_core_loc_conf_t  *clcf;

    	clcf = ngx_http_conf_get_module_loc_conf(cf, ngx_http_core_module);

    	clcf->handler = hexin_http_scribe_handler;

    	return NGX_CONF_OK;
}
Exemplo n.º 5
0
//for now we don't know whether creating python class instance will do write to the class object, then no mutex used, we will check this in detail in the later time
//
int create_ins(void){
    int ret = -1;
    PyObject *pargs=NULL;

#if PY_DEBUG
    fprintf(stderr,"I am here %s\n",__FUNCTION__);
#endif

    if(!check_ready()){
        if(!check_and_set_ready()){
            goto create_ins_error;
        }
    }

	pargs = PyTuple_New(1);
    if(!pargs){
#if PY_DEBUG
		fprintf(stderr,"we cannot create the first tuple\n");  
#endif
        goto create_ins_error;
    }


	PyTuple_SetItem(pargs,0,Py_BuildValue("s",replica_group));

#if PY_DEBUG
	fprintf(stderr,"%p\n",pclass);  
#endif

	pins = PyInstance_New(pclass,pargs,NULL);

	if(!pins){
#if PY_DEBUG
		fprintf(stderr,"we cannot create the instance\n");  
#endif
        goto create_ins_error;
	}
	if(PyInstance_Check(pins)){
#if PY_DEBUG
		fprintf(stderr,"Sure, We have created an instance\n");  
#endif
	}else{
        goto create_ins_error;
    }
    ret = 0;
    goto create_ins_exit;
create_ins_error:
    if(NULL!=pins){Py_DECREF(pins);pins=NULL;};
create_ins_exit:
    if(NULL!=pargs){Py_DECREF(pargs);pargs=NULL;};
    return ret;
}
Exemplo n.º 6
0
PyObject * smds_IPCH_Tabulator_fetch(PyObject *self)
{
  smds_IPCH_Tabulator *t = (smds_IPCH_Tabulator*)self;
  PyObject *o = NULL, *args;
  PyArrayObject *a;
  Int32 *data;
  int i, pos;
  extent *e;
  
  args = Py_BuildValue("(dd)", t->binWidthHist, 
  				(double)t->threshold/t->binWidthHist);
  if (!args) return NULL;
  if (IPCHType) o = PyInstance_New(IPCHType, args, NULL);
  else PyErr_SetString(PyExc_SystemError, "Unable to create IPCH object.");
  if (!o) return NULL;

  i = 0;
  for(e = t->head; e; e = e->next)
    i += e->num;
  if (t->in_event && t->eventPool > i) i = t->eventPool;
  		// Insure enough space for last event
  a = (PyArrayObject*)PyArray_FromDims(1, &i, PyArray_LONG);
  if (!a) { Py_DECREF(o);  return NULL; }
  if (PyObject_SetAttrString(o, "data", (PyObject*)a) == -1)
  {
    Py_DECREF(o);
    Py_DECREF(a);
    return NULL;
  }
  Py_DECREF(a);			// transfered reference to the IPCH object
  data = (Int32*)a->data;

  pos = 0;
  for (e = t->head; e; e = e->next)
    for(i=0; i < e->num; i++, pos++)
      data[pos] = e->data[i];
  
  for (i=pos; i < a->dimensions[0]; i++)
    data[i] = 0;
  if (t->in_event) data[t->eventPool]++;

  return o;
}
Exemplo n.º 7
0
int main(int argc, char ** argv)
{
    loadConfig(argc, argv);

    init_python_api("f5a8a981-e9ac-4f3b-a8f6-528add44da87");

    PyVector3D * pv = newPyVector3D();

    if (PyErr_Occurred() != 0) {
        PyErr_Print();
    }

    PyObject * pv2 = PyInstance_New((PyObject*)&PyVector3D_Type, 0, 0);

    if (PyErr_Occurred() != 0) {
        PyErr_Print();
    }

    shutdown_python_api();
}
Exemplo n.º 8
0
void init_plugin(char* plugin, obj_list container){
	char* myplg = DYN_STR(plugin);
	char* path = (char*)malloc(strlen(plugin)+strlen(PLUGINS_PATH)+1);
	if(isupper(myplg[0])){
		myplg[0] = tolower(myplg[0]);
	}
	strcpy(path, PLUGINS_PATH);
	strcat(path, myplg);
	PyObject* plug_module = PyImport_ImportModule(path);
	if(!plug_module){
		printf("Couldn't import the module plugin module...\n");
		PyErr_Print();
	}
	if(islower(myplg[0])){
		myplg[0] = toupper(myplg[0]);

	}
	PyObject* clazz = PyObject_GetAttrString(plug_module, myplg);
	if(!clazz){
		printf("Couldn't get the plugin class...\n");
		PyErr_Print();
	}
	//TODO check for plugin subclassing
	Py_DECREF(plug_module);
	free(myplg);
	free(path);
	if(!PyClass_Check(clazz)){
		fprintf(stderr, "Got something that wasn't a class object...\n");
	}

	PyObject* plugin_instance = PyInstance_New(clazz, NULL, NULL);
	if(!plugin_instance){
		printf("Couldn't make plugin instance...\n");
		PyErr_Print();
	}
	Py_DECREF(clazz);
	obj_list_add(container, plugin_instance);
}
PyObject* PythonModule_InstatiateClass( PythonModule* Self, char* Name, char* Parameter )
{
  if( Name == NULL || Self == NULL )
    return NULL;

  PyObject* Instance;
  PyObject* Class;

  Class = PyObject_GetAttrString( Self->Module, Name );  
  if( !Class || !PyClass_Check( Class ) )
  {
    PyErr_Print();
    PythonModule_LeaveThread( Self );   
    return NULL;  
  }
  Instance = PyInstance_New( Class, PythonModule_CreateArgument( Parameter ), NULL );
  if( !Instance || !PyInstance_Check( Instance) )
  {
    PyErr_Print();
    PythonModule_LeaveThread( Self );   
    return NULL;  
  }
  return Instance;
}
Exemplo n.º 10
0
int main()
{
    setenv("PYTHONPATH", ".", 1);

    Py_Initialize();

    PyObject* module = PyImport_ImportModule("mymath");
    assert(module != NULL);

    PyObject* klass = PyObject_GetAttrString(module, "math");
    assert(klass != NULL);

    PyObject* instance = PyInstance_New(klass, NULL, NULL);
    assert(instance != NULL);

    PyObject* result = PyObject_CallMethod(instance, "add", "(ii)", 1, 2);
    assert(result != NULL);

    printf("1 + 2 = %ld\n", PyInt_AsLong(result));

    Py_Finalize();

    return 0;
}
Exemplo n.º 11
0
PyObject * smds_core_getResults(PyObject *self)
{
  smds_core *c = (smds_core*)self;
  PyObject *r, *o, *ts = NULL, *counts = NULL;
  extent *e;
  int i, j, base, num;
  
  if (!ResultsType)
  {
    PyErr_SetString(PyExc_SystemError, "Couldn't find ResultsType.");
    return NULL;
  }
  r = PyInstance_New(ResultsType, NULL, NULL);
  if (!r) return NULL;

  o = PyInt_FromLong(c->num);
  if (!o) goto bail;
  if (PyObject_SetAttrString(r, "num", o) == -1) goto bail;
  Py_DECREF(o);

  o = PyInt_FromLong(c->hits);
  if (!o) goto bail;
  if (PyObject_SetAttrString(r, "hits", o) == -1) goto bail;
  Py_DECREF(o);

  o = PyInt_FromLong(c->misses);
  if (!o) goto bail;
  if (PyObject_SetAttrString(r, "misses", o) == -1) goto bail;
  Py_DECREF(o);
  o = NULL;

  j = base = num = 0;
  e = c->timeToHitDist;
  while (e != NULL)
  {
    for (i=0; i < e->num; i++)
      if (e->data[i] > 0) num++;
    e = e->next;
  }

  ts = PyList_New(num);
  if (!ts) goto bail;
  counts = PyList_New(num);
  if (!counts) goto bail;
  e = c->timeToHitDist;
  while (e != NULL)
  {
    for (i=0; i < e->num; i++)
      if (e->data[i] > 0)
      {
        o = PyFloat_FromDouble((base+i)*c->bw*1e-9);
        if (!o) goto bail;
        if (PyList_SetItem(ts, j, o)) goto bail;	// steals ref
        
        o = PyInt_FromLong(e->data[i]);
        if (!o) goto bail;
        if (PyList_SetItem(counts, j, o)) goto bail;	// steals ref
        
        j++;
      }
    base += e->num;
    e = e->next;
  }
  o = NULL;
  if (PyObject_SetAttrString(r, "hitTimeDist_t", ts) == -1) goto bail;
  Py_DECREF(ts);
  ts = NULL;
  if (PyObject_SetAttrString(r, "hitTimeDist_count", counts) == -1) goto bail;
  Py_DECREF(counts);
  counts = NULL;

  return r;
bail:
  Py_DECREF(r);
  if (o) { Py_DECREF(o); }
  if (ts) { Py_DECREF(ts); }
  if (counts) { Py_DECREF(counts); }
  return NULL;    
}
Exemplo n.º 12
0
qd_error_t qd_router_python_setup(qd_router_t *router)
{
    qd_error_clear();
    log_source = qd_log_source("ROUTER");

    qdr_core_route_table_handlers(router->router_core,
                                  router,
                                  qd_router_mobile_added,
                                  qd_router_mobile_removed,
                                  qd_router_link_lost);

    //
    // If we are not operating as an interior router, don't start the
    // router module.
    //
    if (router->router_mode != QD_ROUTER_MODE_INTERIOR)
        return QD_ERROR_NONE;

    PyObject *pDispatchModule = qd_python_module();
    RouterAdapterType.tp_new = PyType_GenericNew;
    PyType_Ready(&RouterAdapterType);
    QD_ERROR_PY_RET();

    PyTypeObject *raType = &RouterAdapterType;
    Py_INCREF(raType);
    PyModule_AddObject(pDispatchModule, "RouterAdapter", (PyObject*) &RouterAdapterType);

    //
    // Attempt to import the Python Router module
    //
    PyObject* pId;
    PyObject* pArea;
    PyObject* pMaxRouters;
    PyObject* pModule;
    PyObject* pClass;
    PyObject* pArgs;

    pModule = PyImport_ImportModule("qpid_dispatch_internal.router");
    QD_ERROR_PY_RET();
    pClass = PyObject_GetAttrString(pModule, "RouterEngine");
    Py_DECREF(pModule);
    QD_ERROR_PY_RET();

    PyObject *adapterType     = PyObject_GetAttrString(pDispatchModule, "RouterAdapter");
    QD_ERROR_PY_RET();
    PyObject *adapterInstance = PyObject_CallObject(adapterType, 0);
    QD_ERROR_PY_RET();

    ((RouterAdapter*) adapterInstance)->router = router;

    //
    // Constructor Arguments for RouterEngine
    //
    pArgs = PyTuple_New(4);

    // arg 0: adapter instance
    PyTuple_SetItem(pArgs, 0, adapterInstance);

    // arg 1: router_id
    pId = PyString_FromString(router->router_id);
    PyTuple_SetItem(pArgs, 1, pId);

    // arg 2: area_id
    pArea = PyString_FromString(router->router_area);
    PyTuple_SetItem(pArgs, 2, pArea);

    // arg 3: max_routers
    pMaxRouters = PyInt_FromLong((long) qd_bitmask_width());
    PyTuple_SetItem(pArgs, 3, pMaxRouters);

    //
    // Instantiate the router
    //
    pyRouter = PyInstance_New(pClass, pArgs, 0);
    Py_DECREF(pArgs);
    Py_DECREF(adapterType);
    QD_ERROR_PY_RET();

    pyTick = PyObject_GetAttrString(pyRouter, "handleTimerTick");
    QD_ERROR_PY_RET();
    pyAdded = PyObject_GetAttrString(pyRouter, "addressAdded");
    QD_ERROR_PY_RET();
    pyRemoved = PyObject_GetAttrString(pyRouter, "addressRemoved");
    QD_ERROR_PY_RET();
    pyLinkLost = PyObject_GetAttrString(pyRouter, "linkLost");
    QD_ERROR_PY_RET();
    return qd_error_code();
}
Exemplo n.º 13
0
/*
This is the main python handler that will transform and treat the client html request. 
return 1 if we have found a python object to treat the requested uri
return 0 if not (page not found)
return -1 in case of problem
return -2 in case the request command is not implemented
*/
int python_handler(struct client *cli)
{
    PyObject *pydict, *pydummy;
    int ret;

    if (debug)
         printf("host=%s,port=%i:python_handler:HEADER:\n%s**\n", cli->remote_addr, cli->remote_port, cli->input_header);
    //  1)initialise environ
    PyObject *pyenviron_class=PyObject_GetAttrString(py_base_module, "Environ");
    if (!pyenviron_class)
    {
         printf("load Environ failed from base module");
         exit(1);
    }
    PyObject *pyenviron=PyObject_CallObject(pyenviron_class, NULL);
    if (!pyenviron)
    {
         printf("Failed to create an instance of Environ");
         exit(1);
    }
    Py_DECREF(pyenviron_class);
    //  2)transform headers into a dictionary and send it to environ.update_headers
    pydict=header_to_dict(cli);
    if (pydict==Py_None)
    {
        Py_DECREF(pyenviron);
        return -500;
    }
    update_environ(pyenviron, pydict, "update_headers");
    Py_DECREF(pydict);   
    //  2bis) we check if the request method is supported
    PyObject *pysupportedhttpcmd = PyObject_GetAttrString(py_base_module, "supported_HTTP_command");
    if (cli->cmd==NULL) pydummy=Py_None; 
    else pydummy = PyString_FromString(cli->cmd);
    if (PySequence_Contains(pysupportedhttpcmd,pydummy)!=1)
    {
        //return not implemented 
        Py_DECREF(pysupportedhttpcmd);
        Py_DECREF(pydummy);
        Py_DECREF(pyenviron);
        return -501;
    }
    Py_DECREF(pydummy);
    //  2ter) we treat directly the OPTIONS command
    if (strcmp(cli->cmd,"OPTIONS")==0)
    {
        pydummy=PyString_FromFormat("HTTP/1.0 200 OK\r\nServer: %s\r\nAllow: ", VERSION) ;
        PyObject *pyitem; 
        int index, max;
        max = PyList_Size(pysupportedhttpcmd);
        for (index=0; index<max; index++)
        {
            pyitem=PyList_GetItem(pysupportedhttpcmd, index);  // no need to decref pyitem
            PyString_Concat(&pydummy, PyObject_Str(pyitem));
            if (index<max-1)
               PyString_Concat(&pydummy, PyString_FromString(", "));
        }
        PyString_Concat(&pydummy, PyString_FromString("\r\nContent-Length: 0\r\n\r\n"));
        cli->response_header = PyString_AsString(pydummy);
	cli->response_header_length=(int)PyString_Size(pydummy);
        cli->response_content=PyList_New(0);
        Py_DECREF(pyenviron);
        return 1;
    }
    Py_DECREF(pysupportedhttpcmd);
    //  3)find if the uri is registered
    if (handle_uri(cli)!=1)
    {
         if (py_generic_cb==NULL)
         {
            //printf("uri not found\n");
            Py_DECREF(pyenviron);
            return 0;
         }
         else
         {
             cli->wsgi_cb=py_generic_cb;
             Py_INCREF(cli->wsgi_cb);
             cli->uri_path=(char *)calloc(1, sizeof(char));
             strcpy(cli->uri_path,"");
         }
    }
    // 4) build path_info, ...
    pydict=py_build_method_variables(cli);
    update_environ(pyenviron, pydict, "update_uri");
    Py_DECREF(pydict);   
    // 5) in case of POST, put it into the wsgi.input
    if (strcmp(cli->cmd,"POST")==0)
    {
        ret=manage_header_body(cli, pyenviron);
        if (ret < 0) {
            return ret;
        }
    }
    //  6) add some request info
    pydict=py_get_request_info(cli);
    update_environ(pyenviron, pydict, "update_from_request");
    Py_DECREF(pydict);
    // 7) build response object
    PyObject *pystart_response_class=PyObject_GetAttrString(py_base_module, "Start_response");
    PyObject *pystart_response=PyInstance_New(pystart_response_class, NULL, NULL);
    Py_DECREF(pystart_response_class);
    if (PyErr_Occurred()) 
    {
             PyErr_Print();
             return -500;
    }
    // 7b) add the current date to the response object
    PyObject *py_response_header=PyObject_GetAttrString(pystart_response,"response_headers");
    char *sftime;
    sftime=cur_time_rfc1123();
    pydummy = PyString_FromString(sftime);
    PyDict_SetItemString(py_response_header, "Date", pydummy);
    Py_DECREF(pydummy);
    Py_DECREF(py_response_header);
    free(sftime);
    pydummy = PyString_FromString(VERSION);
    PyDict_SetItemString(py_response_header, "Server", pydummy);
    Py_DECREF(pydummy);
    
    // 8) execute python callbacks with his parameters
    PyObject *pyarglist = Py_BuildValue("(OO)", pyenviron, pystart_response );
    cli->response_content = PyEval_CallObject(cli->wsgi_cb,pyarglist);
    if (cli->response_content!=NULL) 
    {
        if ((PyFile_Check(cli->response_content)==0) && (PyIter_Check(cli->response_content)==1)) {
            //This is an Iterator object. We have to execute it first
            cli->response_content_obj = cli->response_content;
            cli->response_content = PyIter_Next(cli->response_content_obj);
        }
    }
    Py_DECREF(pyarglist);
    Py_XDECREF(cli->wsgi_cb);
    if (cli->response_content!=NULL) 
    {
        PyObject *pydummy = PyObject_Str(pystart_response);
        cli->response_header = PyString_AsString(pydummy);
	cli->response_header_length = (int)PyString_Size(pydummy);
        Py_DECREF(pydummy);
    }
    else 
    //python call return is NULL
    {
        printf("Python error!!!\n");
        char buff[200];
        sprintf(buff, "HTTP/1.0 500 Not found\r\nContent-Type: text/html\r\nServer: %s* \r\n\r\n", VERSION);
        cli->response_header = buff;

        if (cli->response_header == NULL)
        {
            printf("ERROR!!!! Memory allocation error in the Python error handling procedure\n");
            cli->response_header_length=0;
            goto leave_python_handler;
        } 	
        cli->response_header_length=strlen(cli->response_header);
        
        if (PyErr_Occurred()) 
        { 
             //get_traceback();py_b
             PyObject *pyerrormsg_method=PyObject_GetAttrString(py_base_module,"redirectStdErr");
             PyObject *pyerrormsg=PyObject_CallFunction(pyerrormsg_method, NULL);
             Py_DECREF(pyerrormsg_method);
             Py_DECREF(pyerrormsg);
             PyErr_Print();
             PyObject *pysys=PyObject_GetAttrString(py_base_module,"sys");
             PyObject *pystderr=PyObject_GetAttrString(pysys,"stderr");
             Py_DECREF(pysys);
             PyObject *pygetvalue=PyObject_GetAttrString(pystderr, "getvalue");
             Py_DECREF(pystderr);
             PyObject *pyres=PyObject_CallFunction(pygetvalue, NULL);
             Py_DECREF(pygetvalue);
             printf("%s\n", PyString_AsString(pyres));
             //test if we must send it to the page
             PyObject *pysendtraceback = PyObject_GetAttrString(py_config_module,"send_traceback_to_browser");
             cli->response_content=PyList_New(0);
             if (pysendtraceback==Py_True) {
                pydummy = PyString_FromString("<h1>Error</h1><pre>");
                PyList_Append(cli->response_content, pydummy );
                Py_DECREF(pydummy);
                PyList_Append(cli->response_content, pyres);
                pydummy = PyString_FromString("</pre>");
                PyList_Append(cli->response_content, pydummy);
                Py_DECREF(pydummy);
             } else {
                PyObject *pyshortmsg = PyObject_GetAttrString(py_config_module,"send_traceback_short");
                PyList_Append(cli->response_content, pyshortmsg);
                Py_DECREF(pyshortmsg);
             }
             Py_DECREF(pyres);
             Py_DECREF(pysendtraceback);
         }
         else 
         {
             cli->response_content=PyList_New(0);
             pydummy = PyString_FromString("Page not found.");
             PyList_Append(cli->response_content, pydummy );
             Py_DECREF(pydummy);
         }
    }
leave_python_handler:
    Py_XDECREF(pystart_response);
    Py_XDECREF(pyenviron);
    return 1;
}
Exemplo n.º 14
0
PyObject * smds_Correlator_output(PyObject *self)
{
  smds_Correlator *p = (smds_Correlator *)self;
  PyObject *r = NULL, *o = NULL;
  PyArrayObject *Gs = NULL, *ts = NULL;
  double norm, *G, *t, bin = 0.0;
  int num;
  int i, k, l = 0;			// set l = 1 if g(0) is included

  if (ACFType) r = PyInstance_New(ACFType, NULL, NULL);
  else PyErr_SetString(PyExc_SystemError, "Unable to create ACF object.");
  if (!r)  return NULL;
  
  num = 8*(K+1);				// 129 if g(0) is included
  for (k=1; k < (K+1); k++)
    num -= p->fill[k];
  if (num <= 0)
  {
    Py_DECREF(r);
    Py_RETURN_NONE;
  }
  
  Gs = (PyArrayObject*)PyArray_FromDims(1, &num, PyArray_DOUBLE);
  if (!Gs) goto bail;
  ts = (PyArrayObject*)PyArray_FromDims(1, &num, PyArray_DOUBLE);
  if (!ts) goto bail;
  if (PyObject_SetAttrString(r, "G", (PyObject*)Gs) == -1 ||
      PyObject_SetAttrString(r, "t", (PyObject*)ts) == -1)
    goto bail;
  t = (double*)(ts->data);
  G = (double*)(Gs->data);

/*
  t[0] = 0.0;
  if (!p->sum)
    G[0] = 0.0;
  else
    G[0] = p->G0 / (p->sum*p->sum) * (double)(p->dur);
*/
  
  for (k=1; k < (K+1); k++)
  {
    norm = (double)(p->dur/(1<<(k-1))) / p->M_dir[k];
    for (i=(k==1?-8:0); i < 8-p->fill[k]; i++)
    {
      bin = t[l] = bin + (double)(1 << (k-1)) * p->bw * 1e-3;
      G[l] = norm * p->G[POS(k,i)] / p->M_del[POS(k,i)];
      if (finite(G[l])) l++;
    }
  }
  
  if (l != num)
    Gs->dimensions[0] = ts->dimensions[0] = l;
  
  Py_DECREF(Gs);
  Py_DECREF(ts);
  return r;

bail:
  if (o)  { Py_DECREF(o); }
  if (r)  { Py_DECREF(r); }
  if (Gs) { Py_DECREF(Gs); }
  if (ts) { Py_DECREF(ts); }
  return NULL;
}
Exemplo n.º 15
0
// takes three arguments: numbins, array[short], pos
//    PERFORMS NO CHECKING OF PARAMETERS!
PyObject * smds_core_run(PyObject *self, PyObject *args)
{
  smds_core *s = (smds_core*)self;
  PyArrayObject *o;
  Int16 *iData;
  double *data;
  int dur, pos, i;
  smds_molec *m;
  
  int size, minX, maxX;
  double a;
#ifdef CORE_INTENS
  double *intens = (double*)(s->intens->data);
  double sc_x;
  int numBins_x = s->numBins_x;
#ifdef CORE_3D
  double sc_z;
  int numBins_z = s->numBins_z;
#endif
#else
  int r;
  int threshold;
  double b;
#ifdef CORE_3D
  int threshold_z;
  double c;
#endif
#endif
  double flow_x;
  int dir_flow_x = s->dir_flow_x;
  double t_insert_avg = s->t_insert_avg;
  unsigned long int t_insert = s->t_insert;

  int t, dir, rndCounter = 0;
  unsigned int rnd = 0;
  double *binCount;
  double I;

  if (!PyArg_ParseTuple(args, "iO!i", &dur, &PyArray_Type, &o, &pos))
    return NULL;

  s->dur += dur;
  data = (double*)malloc(sizeof(double)*dur);
  if (!data)
  {
    PyErr_SetString(PyExc_MemoryError, "Unable to allocate working space.");
    return NULL;
  }

  Py_BEGIN_ALLOW_THREADS
  if (s->bkg > 0.0)
    for (i=0; i < dur; i++) data[i] = s->bkg;
  else
    for (i=0; i < dur; i++) data[i] = 0.0;

  binCount = data;
  for (i=dur; i; i--)
  {
    for (t=s->steps; t; t--, t_insert--)
    {
      /* Create new molecules */
      while (!t_insert)
      {
        if (s->avail)
        {
          m = s->avail;
          s->avail = s->avail->next;
        } else {
          m = (smds_molec*)malloc(sizeof(smds_molec));
        }
        m->prev = NULL;
        smds_core_create_molec(m, s, 1);
        if (s->molecs) s->molecs->prev = m;
        m->next = s->molecs;
        s->molecs = m;
        t_insert = (int)(log(DRandom(&s->rs))*t_insert_avg);
      }

      m = s->molecs;
      while (m)
      {
        size = s->size[m->species];
        minX = s->minX[m->species];
        maxX = s->maxX[m->species];
        a = s->a[m->species];
#ifdef CORE_INTENS
        sc_x = s->sc_x[m->species];
#ifdef CORE_3D
        sc_z = s->sc_z[m->species];
#endif
#else
        threshold = s->threshold[m->species];
        b = s->b[m->species];
#ifdef CORE_3D
        threshold_z = s->threshold_z[m->species];
        c = s->c[m->species];
#endif
#endif
        flow_x = s->flow_x[m->species];

        /* Flow */
        if ( ((dir_flow_x > 0) && ((m->x += flow_x) >= maxX)) ||
             ((dir_flow_x < 0) && ((m->x -= flow_x) <  minX)) )
        {
          smds_molec *p = m;
          m = m->next;
          if (p->prev) p->prev->next = p->next;
          else         s->molecs = p->next;		// head of list
          if (p->next) p->next->prev = p->prev;
          // p->prev = NULL;	s->avail is singly-linked.
          p->next = s->avail;
          s->avail = p;
          continue;
        }

        /* Reposition */
#ifdef CORE_3D
        do {
          if (!rndCounter) { rnd = Random(&s->rs);  rndCounter = 10; }
          dir = rnd & 0x7;  rndCounter--;
          rnd >>= 3;
        } while (dir == 6 || dir == 7);
#else
        if (!rndCounter) { rnd = Random(&s->rs);  rndCounter = 16; }
        dir = rnd & 0x3;  rndCounter--;
        rnd >>= 2;
#endif
        switch (dir)
        {
          case 0: m->x++;  if (m->x >= maxX) { m->x = minX;   }  break;
          case 1: m->x--;  if (m->x <  minX) { m->x = maxX-1; }  break;
          case 2: m->y++;  if (m->y >= size) { m->y = -size;  }  break;
          case 3: m->y--;  if (m->y < -size) { m->y = size-1; }  break;
#ifdef CORE_3D
          case 4: m->z++;  if (m->z >= size) { m->z = -size;  }  break;
          case 5: m->z--;  if (m->z < -size) { m->z = size-1; }  break;
#endif
        }

        /* Calculate Intensity */
#ifdef CORE_INTENS
#ifdef CORE_3D
        if (abs((int)(m->x*sc_x)) <= numBins_x &&
            abs((int)(m->y*sc_x)) <= numBins_x &&
            abs((int)(m->z*sc_z)) <= numBins_z)
        {
          I = a * intens[
            (2*numBins_x+1)*(2*numBins_x+1)*(int)(numBins_z + m->z * sc_z) +
            (2*numBins_x+1) * (int)(numBins_x + m->y * sc_x) +
            (int)(numBins_x + m->x * sc_x) ];
#else
        if (abs((int)(x*sc_x)) <= numBins_x &&
            abs((int)(y*sc_x)) <= numBins_x)
        {
          I = a * intens[
            (2*numBins_x+1) * (int)(numBins_x + m->y * sc_x) +
            (int)(numBins_x + m->x * sc_x)  ];
#endif
#else  // not INTENS
#ifdef CORE_3D
        if ( (r = m->x*m->x + m->y*m->y) < threshold && 
             abs(m->z) < threshold_z)
        {
          I = a * exp(b*(double)r + c*(double)(m->z*m->z));
#else
        if ( (r = m->x*m->x + m->y*m->y) < threshold)
        {
          I = a * exp(b * (double)r);
#endif
#endif
#ifdef CORE_BLEACH
          if ((m->photonTolerance -= I) < 0)
          {
            smds_molec *p = m;
            I += m->photonTolerance;
            s->numBleached[m->species]++;
            *binCount += I;

            m = m->next;
            if (p->prev) p->prev->next = p->next;
            else         s->molecs = p->next;		// head of list
            if (p->next) p->next->prev = p->prev;
            p->prev = NULL;
            p->next = s->avail;
            s->avail = p;
            continue;
          }
#endif
          *binCount += I;
        } // in threshold

        m = m->next;
      } // each molecule

    } // each step

    binCount++;
  } // each bin

  s->t_insert = t_insert;

  iData = (Int16*)o->data + pos;
  for (i=0; i < dur; i++)
    s->I += (double)(iData[i] = Poisson(data[i], &s->rs));

  Py_END_ALLOW_THREADS
  free(data);

  Py_RETURN_NONE;
}

PyObject * smds_core_getResults(PyObject *self)
{
  smds_core *c = (smds_core*)self;
  PyObject *r, *o, *l = NULL;
  int i;
  
  if (!ResultsType)
  {
    PyErr_SetString(PyExc_SystemError, "Couldn't find ResultsType.");
    return NULL;
  }
  r = PyInstance_New(ResultsType, NULL, NULL);
  if (!r) return NULL;

  o = PyFloat_FromDouble(c->I/(double)c->dur/c->bw);
  if (!o) goto bail;
  if (PyObject_SetAttrString(r, "avg_I", o) == -1) goto bail;
  Py_DECREF(o);
  
  o = PyFloat_FromDouble((double)c->dur*c->bw*1e-3);
  if (!o) goto bail;
  if (PyObject_SetAttrString(r, "length", o) == -1) goto bail;
  Py_DECREF(o);
  
  l = PyList_New(c->numSpecies);
  if (!l) goto bail;
  for(i=0; i < c->numSpecies; i++)
  {
    o = PyInt_FromLong(c->counts[i]);
    if (!o) goto bail;
    if (PyList_SetItem(l, i, o)) goto bail;	// steals reference
  }
  o = NULL;
  if (PyObject_SetAttrString(r, "counts", l) == -1) goto bail;
  Py_DECREF(l);
  
#ifdef CORE_BLEACH
  l = PyList_New(c->numSpecies);
  if (!l) goto bail;
  for(i=0; i < c->numSpecies; i++)
  {
    o = PyInt_FromLong(c->numBleached[i]);
    if (!o) goto bail;
    if (PyList_SetItem(l, i, o)) goto bail;	// steals reference
  }
  o = NULL;
  if (PyObject_SetAttrString(r, "bleached", l) == -1) goto bail;
  Py_DECREF(l);
#endif
  
  return r;
bail:
  Py_DECREF(r);
  if (o) { Py_DECREF(o); }
  if (l) { Py_DECREF(l); }
  return NULL;    
}

void smds_core_free(smds_core *p)
{
  smds_molec *m;
  if (!p) return;
  free(p->X);
  free(p->a);
#ifdef CORE_BLEACH
  free(p->tol);
#endif
  free(p->size);
  free(p->minX);
  free(p->maxX);
#ifdef CORE_INTENS
  if (p->intens) {  Py_DECREF((PyObject*)p->intens);  }
  free(p->sc_x);
#ifdef CORE_3D
  free(p->sc_z);
#endif
#else
  free(p->threshold);
  free(p->b);
#ifdef CORE_3D
  free(p->c);
  free(p->threshold_z);
#endif
#endif
  free(p->counts);
#ifdef CORE_BLEACH
  free(p->numBleached);
#endif
  free(p->flow_x);
  while (p->molecs)
  {
    m = p->molecs;
    p->molecs = p->molecs->next;
    free(m);
  }
  while (p->avail)
  {
    m = p->avail;
    p->avail = p->avail->next;
    free(m);
  }
  p->ob_type->tp_free((PyObject*)p);
}

PyObject * smds_core_getParamsType(PyObject *cls)
{
  if (ParamsType) { Py_INCREF(ParamsType); }
  return ParamsType;
}

PyObject * smds_core_getResultsType(PyObject *cls)
{
  if (ResultsType) { Py_INCREF(ResultsType); }
  return ResultsType;
}

PyObject * smds_core_getName(PyObject *cls)
{
  return PyString_FromString(str(CORE_NAME));
}

PyObject * smds_core_sRnd(PyObject *self, PyObject *args)
{
  if (PyTuple_Size(args) != 1)
  {
    initRnd();
  }
  else
  {
    int seed;
    if (!PyArg_ParseTuple(args, "k", &seed))
      return NULL;
    seedRnd(seed, NULL);
  }

  Py_RETURN_NONE;
}
Exemplo n.º 16
0
PyObject* pyvle_convert_value(const vle::value::Value& value)
{
    PyObject *pyvle = PyImport_ImportModule("pyvle");
    PyObject* result;

    switch (value.getType()) {
    case vle::value::Value::BOOLEAN: {
        result = PyBool_FromLong(
                vle::value::toBoolean(value));
        break;
    }
    case vle::value::Value::INTEGER: {
        result = PyInt_FromLong(
                vle::value::toInteger(value));
        break;
    }
    case vle::value::Value::DOUBLE: {
        result = PyFloat_FromDouble(
                vle::value::toDouble(value));
        break;
    }
    case vle::value::Value::STRING: {
        result = PyString_FromString(
                vle::value::toString(value).c_str());
        break;
    }
    case vle::value::Value::XMLTYPE: {
        PyObject *class_ = PyObject_GetAttrString(pyvle, "VleXML");
        PyObject* val = PyString_FromString(
                vle::value::toXml(value).c_str());
        PyObject* args = PyTuple_New(1);
        PyTuple_SetItem(args, 0, val);
        result = PyInstance_New(class_, args, NULL);
        break;
    }
    case vle::value::Value::SET: {
        result = PyList_New(0);
        for (vle::value::Set::const_iterator it = value.toSet().begin();
            it != value.toSet().end(); ++it) {
            PyList_Append(result, pyvle_convert_value(**it));
        }
        break;
    }
    case vle::value::Value::MAP: {
        result = PyDict_New();
        for (vle::value::Map::const_iterator it = value.toMap().begin();
            it != value.toMap().end(); ++it) {
            PyDict_SetItemString(result, it->first.c_str(),
                                 pyvle_convert_value(*(it->second)));
        }
        break;
    }
    case vle::value::Value::TUPLE: {
        PyObject *class_ = PyObject_GetAttrString(pyvle, "VleTuple");
        PyObject* val = PyList_New(0);
        std::vector<double>::const_iterator itb =
                value.toTuple().value().begin();
        std::vector<double>::const_iterator ite =
                value.toTuple().value().end();
        for(;itb!=ite;itb++){
            PyList_Append(val, PyFloat_FromDouble(*itb));
        }
        PyObject* args = PyTuple_New(1);
        PyTuple_SetItem(args, 0, val);
        result = PyInstance_New(class_, args, NULL);
        break;
    }
    case vle::value::Value::TABLE: {
        PyObject *class_ = PyObject_GetAttrString(pyvle, "VleTable");
        PyObject* val = PyList_New(0);
        PyObject* r=0;
        const vle::value::Table& t = value.toTable();
        for(unsigned int i=0; i<t.height(); i++){
            r = PyList_New(0);
            for(unsigned int j=0; j<t.width(); j++){
                PyList_Append(r,PyFloat_FromDouble(t.get(j,i)));
            }
            PyList_Append(val,r);
        }
        PyObject* args = PyTuple_New(1);
        PyTuple_SetItem(args, 0, val);
        result = PyInstance_New(class_, args, NULL);
        break;
    }
    case vle::value::Value::MATRIX: {
        PyObject *class_ = PyObject_GetAttrString(pyvle, "VleMatrix");
        PyObject* val = PyList_New(0);
        PyObject* r=0;
        const vle::value::Matrix& t = value.toMatrix();
        for(unsigned int i=0; i<t.rows(); i++){
            r = PyList_New(0);
            for(unsigned int j=0; j<t.columns(); j++){
                PyList_Append(r,pyvle_convert_value(*t.get(j,i)));
            }
            PyList_Append(val,r);
        }
        PyObject* args = PyTuple_New(1);
        PyTuple_SetItem(args, 0, val);
        result = PyInstance_New(class_, args, NULL);
        break;
    }
    default: {
        result = Py_None;
        break;
    }
    }
    return result;
}
Exemplo n.º 17
0
int main(void)
{
	Py_Initialize();
	if(!Py_IsInitialized())
		return -1;
	
	PyRun_SimpleString("import sys");
	//where you put your py file
	PyRun_SimpleString("sys.path.append('../')");
	//Import 
	PyObject* pModule = PyImport_ImportModule("pc");//no *.py
	if(!pModule)
	{
		printf("can't open python file!\n");
		return -1;
	}
	//Dict module
	PyObject* pDict = PyModule_GetDict(pModule);
	if(!pDict)
	{
		printf("can't find dictionary.\n");
		return -1;
	}
	printDict(pDict);

	PyObject *pFunHi = PyDict_GetItemString(pDict, "sayHi");
	PyObject_CallFunction(pFunHi, "s", "yourname");// @para1: obj, @para2: name
	//release
	Py_DECREF(pFunHi);
	
	//Contruct a obj , call it's function
	//Second Class
	PyObject *pClassSecond = PyDict_GetItemString(pDict , "Second");
	if(!pClassSecond)
	{
		printf("can't find second class.\n");
		return -1;
	}
	//Person Class
	PyObject *pClassPerson = PyDict_GetItemString(pDict, "Person");
	if(!pClassPerson)
	{
		printf("can't find Person class.\n");
		return -1;
	}
	//Construct Second Instance
	PyObject* pInstanceSecond = PyInstance_New(pClassSecond, NULL, NULL);
	if(!pInstanceSecond)
	{
		printf("can't create second instance.\n");
		return -1;
	}
	//Construct Person Instance
	PyObject *pInstancePerson = PyInstance_New(pClassPerson, NULL, NULL);
	if(!pInstancePerson)
	{
		printf("can't create Person instance.\n");
		return -1;
	}

	//pass Person Instance to Second Instance 
	PyObject_CallMethod(pInstanceSecond, "invoke", "O", pInstancePerson);
	PyObject_CallMethod(pInstanceSecond, "method2", "O", pInstancePerson);

	//call execute a py file
	PyRun_SimpleString("exec(compile(open('./1.py').read(),'1.py', 'exec'),locals(), globals())");
	//release
	Py_DECREF(pInstanceSecond);
	Py_DECREF(pInstancePerson);
	Py_DECREF(pClassSecond);
	Py_DECREF(pClassPerson);
	Py_DECREF(pModule);
	Py_Finalize();

	return 0;
}
Exemplo n.º 18
0
static PyObject *tibiaauto_tibiaauto_registerPlugin(PyObject *self, PyObject *args)
{
    registerPluginCount++;

    CPythonScript *pythonScript = new CPythonScript();
    CPythonEngine pythonEngine;


    PyObject *pluginClass = NULL;
    if (!PyArg_ParseTuple(args, "O", &pluginClass))
        return NULL;

    Py_XINCREF(pluginClass);
    pythonScript->setPluginClass(pluginClass);

    PyObject *pluginObject = PyInstance_New(pluginClass, NULL, NULL);
    if (pluginObject == NULL)
    {
        AfxMessageBox("registerObject() takes class as an argument");
        Py_XDECREF(pluginClass);
        return NULL;
    }
    Py_XINCREF(pluginObject);
    pythonScript->setPluginObject(pluginObject);

    // getName
    PyObject *result = PyObject_CallMethod(pluginObject, "getName", "()");
    pythonScript->setName(PyString_AsString(result));
    Py_XDECREF(result);

    // getVersion
    result = PyObject_CallMethod(pluginObject, "getVersion", "()");
    pythonScript->setVersion(PyString_AsString(result));
    Py_XDECREF(result);


    // getFunDef
    int nr;
    for (nr = 0;; nr++)
    {
        int type, interval;
        char *matchExpr = NULL;
        int regLen;
        PyObject *periodicalFun;

        result = PyObject_CallMethod(pluginObject, "getFunDef", "(i)", nr);
        if (result == NULL)
        {
            AfxMessageBox("getFunDef() call failed");
            return NULL;
        }

        //nested if statements are for trying to read the two possible sets of parameters
        type = -255;
        if (PyArg_ParseTuple(result, "|iiO", &type, &interval, &periodicalFun))
        {
            if (type != -255)
                pythonScript->addFunDef(type, interval, periodicalFun);
            else
                break;
        }
        else
        {
            PyErr_Clear();
            if (PyArg_ParseTuple(result, "|is#O", &type, &matchExpr, &regLen, &periodicalFun))
            {
                if (type != -255)
                    pythonScript->addFunDef(type, matchExpr, regLen, periodicalFun);
                else
                    break;
            }
            else
            {
                Py_XDECREF(result);
                return NULL;
            }
        }


        Py_XDECREF(result);
    }
    // getConfigParam
    for (nr = 0;; nr++)
    {
        char *name = NULL, *description = NULL;
        result = PyObject_CallMethod(pluginObject, "getConfigParam", "(i)", nr);
        if (result == NULL)
        {
            AfxMessageBox("getConfigParam() call failed");
            return NULL;
        }
        if (PyArg_ParseTuple(result, "|ss", &name, &description))
        {
            if (name != NULL && description != NULL)
                pythonScript->addParamDef(name, description);
            else
                break;
        }
        else
        {
            Py_XDECREF(result);
            return NULL;
        }
        Py_XDECREF(result);
    }


    Py_XDECREF(pluginObject);
    Py_XDECREF(pluginClass);

    Py_INCREF(Py_None);

    return Py_None;
}