static PyObject * PyRRD_info(PyObject UNUSED(*self), PyObject *args) { PyObject *r, *t, *ds; rrd_t rrd; FILE *in_file; char *filename; unsigned long i, j; if (! PyArg_ParseTuple(args, "s:info", &filename)) return NULL; if (rrd_open(filename, &in_file, &rrd, RRD_READONLY) == -1) { PyErr_SetString(ErrorObject, rrd_get_error()); rrd_clear_error(); return NULL; } fclose(in_file); #define DICTSET_STR(dict, name, value) \ t = PyString_FromString(value); \ PyDict_SetItemString(dict, name, t); \ Py_DECREF(t); #define DICTSET_CNT(dict, name, value) \ t = PyInt_FromLong((long)value); \ PyDict_SetItemString(dict, name, t); \ Py_DECREF(t); #define DICTSET_VAL(dict, name, value) \ t = isnan(value) ? (Py_INCREF(Py_None), Py_None) : \ PyFloat_FromDouble((double)value); \ PyDict_SetItemString(dict, name, t); \ Py_DECREF(t); r = PyDict_New(); DICTSET_STR(r, "filename", filename); DICTSET_STR(r, "rrd_version", rrd.stat_head->version); DICTSET_CNT(r, "step", rrd.stat_head->pdp_step); DICTSET_CNT(r, "last_update", rrd.live_head->last_up); ds = PyDict_New(); PyDict_SetItemString(r, "ds", ds); Py_DECREF(ds); for (i = 0; i < rrd.stat_head->ds_cnt; i++) { PyObject *d; d = PyDict_New(); PyDict_SetItemString(ds, rrd.ds_def[i].ds_nam, d); Py_DECREF(d); DICTSET_STR(d, "ds_name", rrd.ds_def[i].ds_nam); DICTSET_STR(d, "type", rrd.ds_def[i].dst); DICTSET_CNT(d, "minimal_heartbeat", rrd.ds_def[i].par[DS_mrhb_cnt].u_cnt); DICTSET_VAL(d, "min", rrd.ds_def[i].par[DS_min_val].u_val); DICTSET_VAL(d, "max", rrd.ds_def[i].par[DS_max_val].u_val); DICTSET_STR(d, "last_ds", rrd.pdp_prep[i].last_ds); DICTSET_VAL(d, "value", rrd.pdp_prep[i].scratch[PDP_val].u_val); DICTSET_CNT(d, "unknown_sec", rrd.pdp_prep[i].scratch[PDP_unkn_sec_cnt].u_cnt); } ds = PyList_New(rrd.stat_head->rra_cnt); PyDict_SetItemString(r, "rra", ds); Py_DECREF(ds); for (i = 0; i < rrd.stat_head->rra_cnt; i++) { PyObject *d, *cdp; d = PyDict_New(); PyList_SET_ITEM(ds, i, d); DICTSET_STR(d, "cf", rrd.rra_def[i].cf_nam); DICTSET_CNT(d, "rows", rrd.rra_def[i].row_cnt); DICTSET_CNT(d, "pdp_per_row", rrd.rra_def[i].pdp_cnt); DICTSET_VAL(d, "xff", rrd.rra_def[i].par[RRA_cdp_xff_val].u_val); cdp = PyList_New(rrd.stat_head->ds_cnt); PyDict_SetItemString(d, "cdp_prep", cdp); Py_DECREF(cdp); for (j = 0; j < rrd.stat_head->ds_cnt; j++) { PyObject *cdd; cdd = PyDict_New(); PyList_SET_ITEM(cdp, j, cdd); DICTSET_VAL(cdd, "value", rrd.cdp_prep[i*rrd.stat_head->ds_cnt+j].scratch[CDP_val].u_val); DICTSET_CNT(cdd, "unknown_datapoints", rrd.cdp_prep[i*rrd.stat_head->ds_cnt+j].scratch[CDP_unkn_pdp_cnt].u_cnt); } } rrd_free(&rrd); return r; }
// Read one table for one sweep value. Returns: // 0 ... performed normally // 1 ... error occurred // Arguments: // f ... pointer to file for reading // debugMode ... debug messages flag // fileName ... name of the file // sweep ... sweep parameter name // numOfVariables ... number of variables in table // type ... type of variables with exeption of scale // numOfVectors ... number of variables and probes in table // faSweep ... pointer to fast access structure for sweep array // tmpArray ... array of pointers to arrays // faPtr ... array of fast access structures for vector arrays // scale ... scale name // name ... array of vector names // dataList ... list of data dictionaries int readTable(FILE *f, int debugMode, int postVersion, const char *fileName, PyObject *sweep, int numOfVariables, int type, int numOfVectors, struct FastArray *faSweep, PyObject **tmpArray, struct FastArray *faPtr, char *scale, char **name, PyObject *dataList) { int i, j, num, offset = 0, numOfColumns = numOfVectors; npy_intp dims; float *rawDataPos, *rawData = NULL; PyObject *data = NULL; // Read raw data blocks. do num = readDataBlock(f, debugMode, postVersion, fileName, &rawData, &offset); while(num == 0); if(num > 0) goto readTableFailed; data = PyDict_New(); // Create an empty dictionary. if(data == NULL) { if(debugMode) fprintf(debugFile, "HSpiceRead: failed to create data dictionary.\n"); goto readTableFailed; } // Increase number of columns if variables with exeption of scale are complex. if(type == complex_var) numOfColumns = numOfColumns + numOfVariables - 1; rawDataPos = rawData; // TODO check sweeps with postVersion == 2001 if(postVersion == 2001) { if(sweep == NULL) num = (offset - 1) / numOfColumns / 2; // Number of rows. else { num = (offset - 2) / numOfColumns / 2; *((npy_double *)(faSweep->pos)) = *((double*)rawDataPos); // Save sweep value. rawDataPos = rawDataPos + 2; faSweep->pos = faSweep->pos + faSweep->stride; } } else { if(sweep == NULL) num = (offset - 1) / numOfColumns; // Number of rows. else { num = (offset - 2) / numOfColumns; *((npy_double *)(faSweep->pos)) = *rawDataPos; // Save sweep value. rawDataPos = rawDataPos + 1; faSweep->pos = faSweep->pos + faSweep->stride; } } if(debugMode) fprintf(debugFile, "num=%d\n", num); for(i = 0; i < numOfVectors; i++) { // Create array for i-th vector. dims=num; if(type == complex_var && i > 0 && i < numOfVariables) tmpArray[i] = PyArray_SimpleNew(1, &dims, PyArray_CDOUBLE); else tmpArray[i] = PyArray_SimpleNew(1, &dims, PyArray_DOUBLE); if(tmpArray[i] == NULL) { if(debugMode) fprintf(debugFile, "HSpiceRead: failed to create array.\n"); for(j = 0; j < i + 1; j++) Py_XDECREF(tmpArray[j]); goto readTableFailed; } } for(i = 0; i < numOfVectors; i++) // Prepare fast access structures. { faPtr[i].data = ((PyArrayObject *)(tmpArray[i]))->data; faPtr[i].pos = ((PyArrayObject *)(tmpArray[i]))->data; faPtr[i].stride = ((PyArrayObject *)(tmpArray[i]))->strides[((PyArrayObject *)(tmpArray[i]))->nd - 1]; faPtr[i].length = PyArray_Size(tmpArray[i]); } if(postVersion == 2001) { for(i = 0; i < num; i++) // Save raw data. { struct FastArray *faPos = faPtr; for(j = 0; j < numOfVectors; j++) { if(type == complex_var && j > 0 && j < numOfVariables) { ((npy_cdouble *)(faPos->pos))->real = *((double *)rawDataPos); rawDataPos = rawDataPos + 2; ((npy_cdouble *)(faPos->pos))->imag = *((double *)rawDataPos); } else *((npy_double *)(faPos->pos)) = *((double *)rawDataPos); rawDataPos = rawDataPos + 2; faPos->pos = faPos->pos + faPos->stride; faPos = faPos + 1; } } } else { for(i = 0; i < num; i++) // Save raw data. { struct FastArray *faPos = faPtr; for(j = 0; j < numOfVectors; j++) { if(type == complex_var && j > 0 && j < numOfVariables) { ((npy_cdouble *)(faPos->pos))->real = *rawDataPos; rawDataPos = rawDataPos + 1; ((npy_cdouble *)(faPos->pos))->imag = *rawDataPos; } else *((npy_double *)(faPos->pos)) = *rawDataPos; rawDataPos = rawDataPos + 1; faPos->pos = faPos->pos + faPos->stride; faPos = faPos + 1; } } } PyMem_Free(rawData); rawData = NULL; // Insert vectors into dictionary. num = PyDict_SetItemString(data, scale, tmpArray[0]); i = -1; if(num == 0) for(i = 0; i < numOfVectors - 1; i++) { num = PyDict_SetItemString(data, name[i], tmpArray[i + 1]); if(num != 0) break; } for(j = 0; j < numOfVectors; j++) Py_XDECREF(tmpArray[j]); if(num) { if(debugMode) { if(i == -1) fprintf(debugFile, "HSpiceRead: failed to insert vector %s into dictionary.\n", scale); else fprintf(debugFile, "HSpiceRead: failed to insert vector %s into dictionary.\n", name[i]); } goto readTableFailed; } // Insert table into the list of data dictionaries. num = PyList_Append(dataList, data); if(num) { if(debugMode) fprintf(debugFile, "HSpiceRead: failed to append table to the list of data dictionaries.\n"); goto readTableFailed; } Py_XDECREF(data); data = NULL; return 0; readTableFailed: PyMem_Free(rawData); Py_XDECREF(data); return 1; }
PyObject *PyInit_test_array_from_pyobj_ext(void) { #else #define RETVAL PyMODINIT_FUNC inittest_array_from_pyobj_ext(void) { #endif PyObject *m,*d, *s; #if PY_VERSION_HEX >= 0x03000000 m = wrap_module = PyModule_Create(&moduledef); #else m = wrap_module = Py_InitModule("test_array_from_pyobj_ext", f2py_module_methods); #endif Py_TYPE(&PyFortran_Type) = &PyType_Type; import_array(); if (PyErr_Occurred()) Py_FatalError("can't initialize module wrap (failed to import numpy)"); d = PyModule_GetDict(m); s = PyString_FromString("This module 'wrap' is auto-generated with f2py (version:2_1330).\nFunctions:\n" " arr = call(type_num,dims,intent,obj)\n" "."); PyDict_SetItemString(d, "__doc__", s); wrap_error = PyErr_NewException ("wrap.error", NULL, NULL); Py_DECREF(s); PyDict_SetItemString(d, "F2PY_INTENT_IN", PyInt_FromLong(F2PY_INTENT_IN)); PyDict_SetItemString(d, "F2PY_INTENT_INOUT", PyInt_FromLong(F2PY_INTENT_INOUT)); PyDict_SetItemString(d, "F2PY_INTENT_OUT", PyInt_FromLong(F2PY_INTENT_OUT)); PyDict_SetItemString(d, "F2PY_INTENT_HIDE", PyInt_FromLong(F2PY_INTENT_HIDE)); PyDict_SetItemString(d, "F2PY_INTENT_CACHE", PyInt_FromLong(F2PY_INTENT_CACHE)); PyDict_SetItemString(d, "F2PY_INTENT_COPY", PyInt_FromLong(F2PY_INTENT_COPY)); PyDict_SetItemString(d, "F2PY_INTENT_C", PyInt_FromLong(F2PY_INTENT_C)); PyDict_SetItemString(d, "F2PY_OPTIONAL", PyInt_FromLong(F2PY_OPTIONAL)); PyDict_SetItemString(d, "F2PY_INTENT_INPLACE", PyInt_FromLong(F2PY_INTENT_INPLACE)); PyDict_SetItemString(d, "PyArray_BOOL", PyInt_FromLong(PyArray_BOOL)); PyDict_SetItemString(d, "PyArray_BYTE", PyInt_FromLong(PyArray_BYTE)); PyDict_SetItemString(d, "PyArray_UBYTE", PyInt_FromLong(PyArray_UBYTE)); PyDict_SetItemString(d, "PyArray_SHORT", PyInt_FromLong(PyArray_SHORT)); PyDict_SetItemString(d, "PyArray_USHORT", PyInt_FromLong(PyArray_USHORT)); PyDict_SetItemString(d, "PyArray_INT", PyInt_FromLong(PyArray_INT)); PyDict_SetItemString(d, "PyArray_UINT", PyInt_FromLong(PyArray_UINT)); PyDict_SetItemString(d, "PyArray_INTP", PyInt_FromLong(PyArray_INTP)); PyDict_SetItemString(d, "PyArray_UINTP", PyInt_FromLong(PyArray_UINTP)); PyDict_SetItemString(d, "PyArray_LONG", PyInt_FromLong(PyArray_LONG)); PyDict_SetItemString(d, "PyArray_ULONG", PyInt_FromLong(PyArray_ULONG)); PyDict_SetItemString(d, "PyArray_LONGLONG", PyInt_FromLong(PyArray_LONGLONG)); PyDict_SetItemString(d, "PyArray_ULONGLONG", PyInt_FromLong(PyArray_ULONGLONG)); PyDict_SetItemString(d, "PyArray_FLOAT", PyInt_FromLong(PyArray_FLOAT)); PyDict_SetItemString(d, "PyArray_DOUBLE", PyInt_FromLong(PyArray_DOUBLE)); PyDict_SetItemString(d, "PyArray_LONGDOUBLE", PyInt_FromLong(PyArray_LONGDOUBLE)); PyDict_SetItemString(d, "PyArray_CFLOAT", PyInt_FromLong(PyArray_CFLOAT)); PyDict_SetItemString(d, "PyArray_CDOUBLE", PyInt_FromLong(PyArray_CDOUBLE)); PyDict_SetItemString(d, "PyArray_CLONGDOUBLE", PyInt_FromLong(PyArray_CLONGDOUBLE)); PyDict_SetItemString(d, "PyArray_OBJECT", PyInt_FromLong(PyArray_OBJECT)); PyDict_SetItemString(d, "PyArray_STRING", PyInt_FromLong(PyArray_STRING)); PyDict_SetItemString(d, "PyArray_UNICODE", PyInt_FromLong(PyArray_UNICODE)); PyDict_SetItemString(d, "PyArray_VOID", PyInt_FromLong(PyArray_VOID)); PyDict_SetItemString(d, "PyArray_NTYPES", PyInt_FromLong(PyArray_NTYPES)); PyDict_SetItemString(d, "PyArray_NOTYPE", PyInt_FromLong(PyArray_NOTYPE)); PyDict_SetItemString(d, "PyArray_UDERDEF", PyInt_FromLong(PyArray_USERDEF)); PyDict_SetItemString(d, "CONTIGUOUS", PyInt_FromLong(NPY_CONTIGUOUS)); PyDict_SetItemString(d, "FORTRAN", PyInt_FromLong(NPY_FORTRAN)); PyDict_SetItemString(d, "OWNDATA", PyInt_FromLong(NPY_OWNDATA)); PyDict_SetItemString(d, "FORCECAST", PyInt_FromLong(NPY_FORCECAST)); PyDict_SetItemString(d, "ENSURECOPY", PyInt_FromLong(NPY_ENSURECOPY)); PyDict_SetItemString(d, "ENSUREARRAY", PyInt_FromLong(NPY_ENSUREARRAY)); PyDict_SetItemString(d, "ALIGNED", PyInt_FromLong(NPY_ALIGNED)); PyDict_SetItemString(d, "WRITEABLE", PyInt_FromLong(NPY_WRITEABLE)); PyDict_SetItemString(d, "UPDATEIFCOPY", PyInt_FromLong(NPY_UPDATEIFCOPY)); PyDict_SetItemString(d, "BEHAVED", PyInt_FromLong(NPY_BEHAVED)); PyDict_SetItemString(d, "BEHAVED_NS", PyInt_FromLong(NPY_BEHAVED_NS)); PyDict_SetItemString(d, "CARRAY", PyInt_FromLong(NPY_CARRAY)); PyDict_SetItemString(d, "FARRAY", PyInt_FromLong(NPY_FARRAY)); PyDict_SetItemString(d, "CARRAY_RO", PyInt_FromLong(NPY_CARRAY_RO)); PyDict_SetItemString(d, "FARRAY_RO", PyInt_FromLong(NPY_FARRAY_RO)); PyDict_SetItemString(d, "DEFAULT", PyInt_FromLong(NPY_DEFAULT)); PyDict_SetItemString(d, "UPDATE_ALL", PyInt_FromLong(NPY_UPDATE_ALL)); if (PyErr_Occurred()) Py_FatalError("can't initialize module wrap"); #ifdef F2PY_REPORT_ATEXIT on_exit(f2py_report_on_exit,(void*)"array_from_pyobj.wrap.call"); #endif return RETVAL; }
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; if(PyDict_SetItemString(deviceInfo, "sampleRates", sampleRates)) goto fail; if(PyDict_SetItemString(deviceInfo, "nativeFormats", nativeFormats)) goto fail; return deviceInfo; fail: Py_XDECREF(name); Py_XDECREF(probed); Py_XDECREF(outputChannels); Py_XDECREF(inputChannels); Py_XDECREF(duplexChannels); Py_XDECREF(isDefault); Py_XDECREF(sampleRates); Py_XDECREF(nativeFormats); Py_XDECREF(deviceInfo); return NULL; }
bool mitk::PythonService::CopyToPythonAsSimpleItkImage(mitk::Image *image, const std::string &stdvarName) { QString varName = QString::fromStdString( stdvarName ); QString command; unsigned int* imgDim = image->GetDimensions(); int npy_nd = 1; npy_intp* npy_dims = new npy_intp[1]; npy_dims[0] = imgDim[0] * imgDim[1] * imgDim[2]; // access python module PyObject *pyMod = PyImport_AddModule((char*)"__main__"); // global dictionarry PyObject *pyDict = PyModule_GetDict(pyMod); const mitk::Vector3D spacing = image->GetGeometry()->GetSpacing(); const mitk::Point3D origin = image->GetGeometry()->GetOrigin(); mitk::PixelType pixelType = image->GetPixelType(); itk::ImageIOBase::IOPixelType ioPixelType = image->GetPixelType().GetPixelType(); PyObject* npyArray = NULL; mitk::ImageReadAccessor racc(image); void* array = (void*) racc.GetData(); // default pixeltype: unsigned short NPY_TYPES npy_type = NPY_USHORT; std::string sitk_type = "sitkUInt8"; if( ioPixelType == itk::ImageIOBase::SCALAR ) { if( pixelType.GetComponentType() == itk::ImageIOBase::DOUBLE ) { npy_type = NPY_DOUBLE; sitk_type = "sitkFloat64"; } else if( pixelType.GetComponentType() == itk::ImageIOBase::FLOAT ) { npy_type = NPY_FLOAT; sitk_type = "sitkFloat32"; } else if( pixelType.GetComponentType() == itk::ImageIOBase::SHORT) { npy_type = NPY_SHORT; sitk_type = "sitkInt16"; } else if( pixelType.GetComponentType() == itk::ImageIOBase::CHAR ) { npy_type = NPY_BYTE; sitk_type = "sitkInt8"; } else if( pixelType.GetComponentType() == itk::ImageIOBase::INT ) { npy_type = NPY_INT; sitk_type = "sitkInt32"; } else if( pixelType.GetComponentType() == itk::ImageIOBase::LONG ) { npy_type = NPY_LONG; sitk_type = "sitkInt64"; } else if( pixelType.GetComponentType() == itk::ImageIOBase::UCHAR ) { npy_type = NPY_UBYTE; sitk_type = "sitkUInt8"; } else if( pixelType.GetComponentType() == itk::ImageIOBase::UINT ) { npy_type = NPY_UINT; sitk_type = "sitkUInt32"; } else if( pixelType.GetComponentType() == itk::ImageIOBase::ULONG ) { npy_type = NPY_LONG; sitk_type = "sitkUInt64"; } else if( pixelType.GetComponentType() == itk::ImageIOBase::USHORT ) { npy_type = NPY_USHORT; sitk_type = "sitkUInt16"; } } else { MITK_WARN << "not a scalar pixeltype"; return false; } // creating numpy array import_array1 (true); npyArray = PyArray_SimpleNewFromData(npy_nd,npy_dims,npy_type,array); // add temp array it to the python dictionary to access it in python code const int status = PyDict_SetItemString( pyDict,QString("%1_numpy_array") .arg(varName).toStdString().c_str(), npyArray ); // sanity check if ( status != 0 ) return false; command.append( QString("%1 = sitk.Image(%2,%3,%4,sitk.%5)\n").arg(varName) .arg(QString::number(imgDim[0])) .arg(QString::number(imgDim[1])) .arg(QString::number(imgDim[2])) .arg(QString(sitk_type.c_str())) ); command.append( QString("%1.SetSpacing([%2,%3,%4])\n").arg(varName) .arg(QString::number(spacing[0])) .arg(QString::number(spacing[1])) .arg(QString::number(spacing[2])) ); command.append( QString("%1.SetOrigin([%2,%3,%4])\n").arg(varName) .arg(QString::number(origin[0])) .arg(QString::number(origin[1])) .arg(QString::number(origin[2])) ); // directly access the cpp api from the lib command.append( QString("_SimpleITK._SetImageFromArray(%1_numpy_array,%1)\n").arg(varName) ); command.append( QString("del %1_numpy_array").arg(varName) ); MITK_DEBUG("PythonService") << "Issuing python command " << command.toStdString(); this->Execute( command.toStdString(), IPythonService::MULTI_LINE_COMMAND ); return true; }
static PyObject * python_orbstat( PyObject *self, PyObject *args ) { char *usage = "Usage: _orbstat(orb)\n"; int orbfd; Orbstat *os = 0; char *ip; struct in_addr addr; int rc; PyObject *obj; if( ! PyArg_ParseTuple( args, "i", &orbfd ) ) { if( ! PyErr_Occurred() ) { PyErr_SetString( PyExc_RuntimeError, usage ); } return NULL; } rc = orbstat( orbfd, &os ); if( rc < 0 ) { PyErr_SetString( PyExc_RuntimeError, "error querying orb status" ); return NULL; } memcpy( &addr.s_addr, &os->address, 4 ); ip = inet_ntoa( addr ); obj = PyDict_New(); PyDict_SetItemString( obj, "when", Py_BuildValue( "f", os->when ) ); PyDict_SetItemString( obj, "started", Py_BuildValue( "f", os->started ) ); PyDict_SetItemString( obj, "orb_start", Py_BuildValue( "f", os->orb_start ) ); PyDict_SetItemString( obj, "connections", Py_BuildValue( "i", os->connections ) ); PyDict_SetItemString( obj, "messages", Py_BuildValue( "i", os->messages ) ); PyDict_SetItemString( obj, "maxdata", PyInt_FromLong( (long) os->maxdata ) ); PyDict_SetItemString( obj, "errors", Py_BuildValue( "i", os->errors ) ); PyDict_SetItemString( obj, "rejected", Py_BuildValue( "i", os->rejected ) ); PyDict_SetItemString( obj, "closes", Py_BuildValue( "i", os->closes ) ); PyDict_SetItemString( obj, "opens", Py_BuildValue( "i", os->opens ) ); PyDict_SetItemString( obj, "port", Py_BuildValue( "i", os->port ) ); PyDict_SetItemString( obj, "address", Py_BuildValue( "s", ip ) ); PyDict_SetItemString( obj, "pid", Py_BuildValue( "i", os->pid ) ); PyDict_SetItemString( obj, "nsources", Py_BuildValue( "i", os->nsources ) ); PyDict_SetItemString( obj, "nclients", Py_BuildValue( "i", os->nclients ) ); PyDict_SetItemString( obj, "maxsrc", Py_BuildValue( "i", os->maxsrc ) ); PyDict_SetItemString( obj, "maxpkts", Py_BuildValue( "i", os->maxpkts ) ); PyDict_SetItemString( obj, "version", Py_BuildValue( "s", os->version ) ); PyDict_SetItemString( obj, "who", Py_BuildValue( "s", os->who ) ); PyDict_SetItemString( obj, "host", Py_BuildValue( "s", os->host ) ); return obj; }
// // generalized function for setting up a dictionary and running a trigger. The // common types of variables can be supplied in the function. Additional ones // can be added in the optional list, which must be deleted after use void gen_do_trig(TRIGGER_DATA *trig, void *me, int me_type, CHAR_DATA *ch, OBJ_DATA *obj, ROOM_DATA *room, EXIT_DATA *exit, const char *command, const char *arg, LIST *optional) { // make our basic dictionary, and fill it up with these new variables PyObject *dict = restricted_script_dict(); LIST *varnames = newList(); // now, import all of our variables if(command) { PyObject *pycmd = PyString_FromString(command); PyDict_SetItemString(dict, "cmd", pycmd); listPut(varnames, strdup("cmd")); Py_DECREF(pycmd); } if(arg) { PyObject *pyarg = PyString_FromString(arg); PyDict_SetItemString(dict, "arg", pyarg); listPut(varnames, strdup("arg")); Py_DECREF(pyarg); } if(ch) { PyObject *pych = charGetPyForm(ch); PyDict_SetItemString(dict, "ch", pych); listPut(varnames, strdup("ch")); Py_DECREF(pych); } if(room) { PyObject *pyroom = roomGetPyForm(room); PyDict_SetItemString(dict, "room", pyroom); listPut(varnames, strdup("room")); Py_DECREF(pyroom); } if(obj) { PyObject *pyobj = objGetPyForm(obj); PyDict_SetItemString(dict, "obj", pyobj); listPut(varnames, strdup("obj")); Py_DECREF(pyobj); } if(exit) { PyObject *pyexit = newPyExit(exit); PyDict_SetItemString(dict, "ex", pyexit); listPut(varnames, strdup("ex")); Py_DECREF(pyexit); } // add the thing the tirgger is attached to if(me) { PyObject *pyme = NULL; switch(me_type) { case TRIGVAR_CHAR: pyme = charGetPyForm(me); break; case TRIGVAR_OBJ: pyme = objGetPyForm(me); break; case TRIGVAR_ROOM: pyme = roomGetPyForm(me); break; } PyDict_SetItemString(dict, "me", pyme); listPut(varnames, strdup("me")); Py_DECREF(pyme); } // now, add any optional variables if(optional) { LIST_ITERATOR *opt_i = newListIterator(optional); OPT_VAR *opt = NULL; PyObject *pyopt = NULL; ITERATE_LIST(opt, opt_i) { pyopt = NULL; switch(opt->type) { case TRIGVAR_CHAR: pyopt = charGetPyForm(opt->data); break; case TRIGVAR_OBJ: pyopt = objGetPyForm(opt->data); break; case TRIGVAR_ROOM: pyopt = roomGetPyForm(opt->data); break; } PyDict_SetItemString(dict, opt->name, pyopt); listPut(varnames, strdup(opt->name)); Py_XDECREF(pyopt); } deleteListIterator(opt_i); }
PyMODINIT_FUNC PyInit_mathutils(void) { PyObject *mod; PyObject *submodule; PyObject *sys_modules = PyThreadState_GET()->interp->modules; if (PyType_Ready(&vector_Type) < 0) return NULL; if (PyType_Ready(&matrix_Type) < 0) return NULL; if (PyType_Ready(&matrix_access_Type) < 0) return NULL; if (PyType_Ready(&euler_Type) < 0) return NULL; if (PyType_Ready(&quaternion_Type) < 0) return NULL; if (PyType_Ready(&color_Type) < 0) return NULL; mod = PyModule_Create(&M_Mathutils_module_def); /* each type has its own new() function */ PyModule_AddObject(mod, vector_Type.tp_name, (PyObject *)&vector_Type); PyModule_AddObject(mod, matrix_Type.tp_name, (PyObject *)&matrix_Type); PyModule_AddObject(mod, euler_Type.tp_name, (PyObject *)&euler_Type); PyModule_AddObject(mod, quaternion_Type.tp_name, (PyObject *)&quaternion_Type); PyModule_AddObject(mod, color_Type.tp_name, (PyObject *)&color_Type); /* submodule */ PyModule_AddObject(mod, "geometry", (submodule = PyInit_mathutils_geometry())); /* XXX, python doesnt do imports with this usefully yet * 'from mathutils.geometry import PolyFill' * ...fails without this. */ PyDict_SetItemString(sys_modules, PyModule_GetName(submodule), submodule); Py_INCREF(submodule); PyModule_AddObject(mod, "interpolate", (submodule = PyInit_mathutils_interpolate())); /* XXX, python doesnt do imports with this usefully yet * 'from mathutils.geometry import PolyFill' * ...fails without this. */ PyDict_SetItemString(sys_modules, PyModule_GetName(submodule), submodule); Py_INCREF(submodule); #ifndef MATH_STANDALONE /* Noise submodule */ PyModule_AddObject(mod, "noise", (submodule = PyInit_mathutils_noise())); PyDict_SetItemString(sys_modules, PyModule_GetName(submodule), submodule); Py_INCREF(submodule); /* BVHTree submodule */ PyModule_AddObject(mod, "bvhtree", (submodule = PyInit_mathutils_bvhtree())); PyDict_SetItemString(sys_modules, PyModule_GetName(submodule), submodule); Py_INCREF(submodule); /* KDTree submodule */ PyModule_AddObject(mod, "kdtree", (submodule = PyInit_mathutils_kdtree())); PyDict_SetItemString(sys_modules, PyModule_GetName(submodule), submodule); Py_INCREF(submodule); #endif mathutils_matrix_row_cb_index = Mathutils_RegisterCallback(&mathutils_matrix_row_cb); mathutils_matrix_col_cb_index = Mathutils_RegisterCallback(&mathutils_matrix_col_cb); mathutils_matrix_translation_cb_index = Mathutils_RegisterCallback(&mathutils_matrix_translation_cb); return mod; }
static PyObject *GPU_export_shader(PyObject *UNUSED(self), PyObject *args, PyObject *kwds) { PyObject *pyscene; PyObject *pymat; PyObject *result; PyObject *dict; PyObject *val; PyObject *seq; int i; Scene *scene; PointerRNA tptr; Material *material; GPUShaderExport *shader; GPUInputUniform *uniform; GPUInputAttribute *attribute; static const char *kwlist[] = {"scene", "material", NULL}; if (!PyArg_ParseTupleAndKeywords(args, kwds, "OO:export_shader", (char **)(kwlist), &pyscene, &pymat)) return NULL; scene = (Scene *)PyC_RNA_AsPointer(pyscene, "Scene"); if (scene == NULL) { return NULL; } material = (Material *)PyC_RNA_AsPointer(pymat, "Material"); if (material == NULL) { return NULL; } /* we can call our internal function at last: */ shader = GPU_shader_export(scene, material); if (!shader) { PyErr_SetString(PyExc_RuntimeError, "cannot export shader"); return NULL; } /* build a dictionary */ result = PyDict_New(); if (shader->fragment) { PY_DICT_ADD_STRING(result, shader, fragment); } if (shader->vertex) { PY_DICT_ADD_STRING(result, shader, vertex); } seq = PyList_New(BLI_listbase_count(&shader->uniforms)); for (i = 0, uniform = shader->uniforms.first; uniform; uniform = uniform->next, i++) { dict = PyDict_New(); PY_DICT_ADD_STRING(dict, uniform, varname); PY_DICT_ADD_LONG(dict, uniform, datatype); PY_DICT_ADD_LONG(dict, uniform, type); if (uniform->lamp) { PY_DICT_ADD_ID(dict, uniform, lamp); } if (uniform->image) { PY_DICT_ADD_ID(dict, uniform, image); } if (uniform->type == GPU_DYNAMIC_SAMPLER_2DBUFFER || uniform->type == GPU_DYNAMIC_SAMPLER_2DIMAGE || uniform->type == GPU_DYNAMIC_SAMPLER_2DSHADOW) { PY_DICT_ADD_LONG(dict, uniform, texnumber); } if (uniform->texpixels) { val = PyByteArray_FromStringAndSize((const char *)uniform->texpixels, uniform->texsize * 4); PyDict_SetItemString(dict, "texpixels", val); Py_DECREF(val); PY_DICT_ADD_LONG(dict, uniform, texsize); } PyList_SET_ITEM(seq, i, dict); } PyDict_SetItemString(result, "uniforms", seq); Py_DECREF(seq); seq = PyList_New(BLI_listbase_count(&shader->attributes)); for (i = 0, attribute = shader->attributes.first; attribute; attribute = attribute->next, i++) { dict = PyDict_New(); PY_DICT_ADD_STRING(dict, attribute, varname); PY_DICT_ADD_LONG(dict, attribute, datatype); PY_DICT_ADD_LONG(dict, attribute, type); PY_DICT_ADD_LONG(dict, attribute, number); if (attribute->name) { if (attribute->name[0] != 0) { PY_DICT_ADD_STRING(dict, attribute, name); } else { val = PyLong_FromLong(0); PyDict_SetItemString(dict, "name", val); Py_DECREF(val); } } PyList_SET_ITEM(seq, i, dict); } PyDict_SetItemString(result, "attributes", seq); Py_DECREF(seq); GPU_free_shader_export(shader); return result; }
/* Shared python2/3 module initialization: */ static int initModule(PyObject *m) { PyObject * d; /* * treat error to register rpm cleanup hook as fatal, tracebacks * can and will leave stale locks around if we can't clean up */ if (Py_AtExit(rpm_exithook) == -1) return 0; /* failure to initialize rpm (crypto and all) is rather fatal too... */ if (rpmReadConfigFiles(NULL, NULL) == -1) return 0; d = PyModule_GetDict(m); pyrpmError = PyErr_NewException("_rpm.error", NULL, NULL); if (pyrpmError != NULL) PyDict_SetItemString(d, "error", pyrpmError); Py_INCREF(&hdr_Type); PyModule_AddObject(m, "hdr", (PyObject *) &hdr_Type); Py_INCREF(&rpmds_Type); PyModule_AddObject(m, "ds", (PyObject *) &rpmds_Type); Py_INCREF(&rpmfd_Type); PyModule_AddObject(m, "fd", (PyObject *) &rpmfd_Type); Py_INCREF(&rpmfi_Type); PyModule_AddObject(m, "fi", (PyObject *) &rpmfi_Type); Py_INCREF(&rpmKeyring_Type); PyModule_AddObject(m, "keyring", (PyObject *) &rpmKeyring_Type); Py_INCREF(&rpmmi_Type); PyModule_AddObject(m, "mi", (PyObject *) &rpmmi_Type); Py_INCREF(&rpmii_Type); PyModule_AddObject(m, "ii", (PyObject *) &rpmii_Type); Py_INCREF(&rpmProblem_Type); PyModule_AddObject(m, "prob", (PyObject *) &rpmProblem_Type); Py_INCREF(&rpmPubkey_Type); PyModule_AddObject(m, "pubkey", (PyObject *) &rpmPubkey_Type); #if 0 Py_INCREF(&rpmtd_Type); PyModule_AddObject(m, "td", (PyObject *) &rpmtd_Type); #endif Py_INCREF(&rpmte_Type); PyModule_AddObject(m, "te", (PyObject *) &rpmte_Type); Py_INCREF(&rpmts_Type); PyModule_AddObject(m, "ts", (PyObject *) &rpmts_Type); addRpmTags(m); PyModule_AddStringConstant(m, "__version__", RPMVERSION); #define REGISTER_ENUM(val) PyModule_AddIntConstant(m, #val, val) REGISTER_ENUM(RPMTAG_NOT_FOUND); REGISTER_ENUM(RPMRC_OK); REGISTER_ENUM(RPMRC_NOTFOUND); REGISTER_ENUM(RPMRC_FAIL); REGISTER_ENUM(RPMRC_NOTTRUSTED); REGISTER_ENUM(RPMRC_NOKEY); REGISTER_ENUM(RPMFILE_STATE_NORMAL); REGISTER_ENUM(RPMFILE_STATE_REPLACED); REGISTER_ENUM(RPMFILE_STATE_NOTINSTALLED); REGISTER_ENUM(RPMFILE_STATE_NETSHARED); REGISTER_ENUM(RPMFILE_STATE_WRONGCOLOR); REGISTER_ENUM(RPMFILE_CONFIG); REGISTER_ENUM(RPMFILE_DOC); REGISTER_ENUM(RPMFILE_MISSINGOK); REGISTER_ENUM(RPMFILE_NOREPLACE); REGISTER_ENUM(RPMFILE_GHOST); REGISTER_ENUM(RPMFILE_LICENSE); REGISTER_ENUM(RPMFILE_README); REGISTER_ENUM(RPMFILE_PUBKEY); REGISTER_ENUM(RPMDEP_SENSE_REQUIRES); REGISTER_ENUM(RPMDEP_SENSE_CONFLICTS); REGISTER_ENUM(RPMSENSE_ANY); REGISTER_ENUM(RPMSENSE_LESS); REGISTER_ENUM(RPMSENSE_GREATER); REGISTER_ENUM(RPMSENSE_EQUAL); REGISTER_ENUM(RPMSENSE_POSTTRANS); REGISTER_ENUM(RPMSENSE_PREREQ); REGISTER_ENUM(RPMSENSE_PRETRANS); REGISTER_ENUM(RPMSENSE_INTERP); REGISTER_ENUM(RPMSENSE_SCRIPT_PRE); REGISTER_ENUM(RPMSENSE_SCRIPT_POST); REGISTER_ENUM(RPMSENSE_SCRIPT_PREUN); REGISTER_ENUM(RPMSENSE_SCRIPT_POSTUN); REGISTER_ENUM(RPMSENSE_SCRIPT_VERIFY); REGISTER_ENUM(RPMSENSE_FIND_REQUIRES); REGISTER_ENUM(RPMSENSE_FIND_PROVIDES); REGISTER_ENUM(RPMSENSE_TRIGGERIN); REGISTER_ENUM(RPMSENSE_TRIGGERUN); REGISTER_ENUM(RPMSENSE_TRIGGERPOSTUN); REGISTER_ENUM(RPMSENSE_RPMLIB); REGISTER_ENUM(RPMSENSE_TRIGGERPREIN); REGISTER_ENUM(RPMSENSE_KEYRING); REGISTER_ENUM(RPMSENSE_CONFIG); REGISTER_ENUM(RPMTRANS_FLAG_TEST); REGISTER_ENUM(RPMTRANS_FLAG_BUILD_PROBS); REGISTER_ENUM(RPMTRANS_FLAG_NOSCRIPTS); REGISTER_ENUM(RPMTRANS_FLAG_JUSTDB); REGISTER_ENUM(RPMTRANS_FLAG_NOTRIGGERS); REGISTER_ENUM(RPMTRANS_FLAG_NODOCS); REGISTER_ENUM(RPMTRANS_FLAG_ALLFILES); REGISTER_ENUM(RPMTRANS_FLAG_KEEPOBSOLETE); REGISTER_ENUM(RPMTRANS_FLAG_NOCONTEXTS); REGISTER_ENUM(RPMTRANS_FLAG_REPACKAGE); REGISTER_ENUM(RPMTRANS_FLAG_REVERSE); REGISTER_ENUM(RPMTRANS_FLAG_NOPRE); REGISTER_ENUM(RPMTRANS_FLAG_NOPOST); REGISTER_ENUM(RPMTRANS_FLAG_NOTRIGGERPREIN); REGISTER_ENUM(RPMTRANS_FLAG_NOTRIGGERIN); REGISTER_ENUM(RPMTRANS_FLAG_NOTRIGGERUN); REGISTER_ENUM(RPMTRANS_FLAG_NOPREUN); REGISTER_ENUM(RPMTRANS_FLAG_NOPOSTUN); REGISTER_ENUM(RPMTRANS_FLAG_NOTRIGGERPOSTUN); REGISTER_ENUM(RPMTRANS_FLAG_NOPRETRANS); REGISTER_ENUM(RPMTRANS_FLAG_NOPOSTTRANS); REGISTER_ENUM(RPMTRANS_FLAG_NOMD5); REGISTER_ENUM(RPMTRANS_FLAG_NOFILEDIGEST); REGISTER_ENUM(RPMTRANS_FLAG_NOSUGGEST); REGISTER_ENUM(RPMTRANS_FLAG_ADDINDEPS); REGISTER_ENUM(RPMTRANS_FLAG_NOCONFIGS); REGISTER_ENUM(RPMPROB_FILTER_IGNOREOS); REGISTER_ENUM(RPMPROB_FILTER_IGNOREARCH); REGISTER_ENUM(RPMPROB_FILTER_REPLACEPKG); REGISTER_ENUM(RPMPROB_FILTER_FORCERELOCATE); REGISTER_ENUM(RPMPROB_FILTER_REPLACENEWFILES); REGISTER_ENUM(RPMPROB_FILTER_REPLACEOLDFILES); REGISTER_ENUM(RPMPROB_FILTER_OLDPACKAGE); REGISTER_ENUM(RPMPROB_FILTER_DISKSPACE); REGISTER_ENUM(RPMPROB_FILTER_DISKNODES); REGISTER_ENUM(RPMCALLBACK_UNKNOWN); REGISTER_ENUM(RPMCALLBACK_INST_PROGRESS); REGISTER_ENUM(RPMCALLBACK_INST_START); REGISTER_ENUM(RPMCALLBACK_INST_OPEN_FILE); REGISTER_ENUM(RPMCALLBACK_INST_CLOSE_FILE); REGISTER_ENUM(RPMCALLBACK_TRANS_PROGRESS); REGISTER_ENUM(RPMCALLBACK_TRANS_START); REGISTER_ENUM(RPMCALLBACK_TRANS_STOP); REGISTER_ENUM(RPMCALLBACK_UNINST_PROGRESS); REGISTER_ENUM(RPMCALLBACK_UNINST_START); REGISTER_ENUM(RPMCALLBACK_UNINST_STOP); REGISTER_ENUM(RPMCALLBACK_REPACKAGE_PROGRESS); REGISTER_ENUM(RPMCALLBACK_REPACKAGE_START); REGISTER_ENUM(RPMCALLBACK_REPACKAGE_STOP); REGISTER_ENUM(RPMCALLBACK_UNPACK_ERROR); REGISTER_ENUM(RPMCALLBACK_CPIO_ERROR); REGISTER_ENUM(RPMCALLBACK_SCRIPT_ERROR); REGISTER_ENUM(RPMCALLBACK_SCRIPT_START); REGISTER_ENUM(RPMCALLBACK_SCRIPT_STOP); REGISTER_ENUM(RPMCALLBACK_INST_STOP); REGISTER_ENUM(RPMPROB_BADARCH); REGISTER_ENUM(RPMPROB_BADOS); REGISTER_ENUM(RPMPROB_PKG_INSTALLED); REGISTER_ENUM(RPMPROB_BADRELOCATE); REGISTER_ENUM(RPMPROB_REQUIRES); REGISTER_ENUM(RPMPROB_CONFLICT); REGISTER_ENUM(RPMPROB_NEW_FILE_CONFLICT); REGISTER_ENUM(RPMPROB_FILE_CONFLICT); REGISTER_ENUM(RPMPROB_OLDPACKAGE); REGISTER_ENUM(RPMPROB_DISKSPACE); REGISTER_ENUM(RPMPROB_DISKNODES); REGISTER_ENUM(RPMPROB_OBSOLETES); REGISTER_ENUM(VERIFY_DIGEST); REGISTER_ENUM(VERIFY_SIGNATURE); REGISTER_ENUM(RPMLOG_EMERG); REGISTER_ENUM(RPMLOG_ALERT); REGISTER_ENUM(RPMLOG_CRIT); REGISTER_ENUM(RPMLOG_ERR); REGISTER_ENUM(RPMLOG_WARNING); REGISTER_ENUM(RPMLOG_NOTICE); REGISTER_ENUM(RPMLOG_INFO); REGISTER_ENUM(RPMLOG_DEBUG); REGISTER_ENUM(RPMMIRE_DEFAULT); REGISTER_ENUM(RPMMIRE_STRCMP); REGISTER_ENUM(RPMMIRE_REGEX); REGISTER_ENUM(RPMMIRE_GLOB); REGISTER_ENUM(RPMVSF_DEFAULT); REGISTER_ENUM(RPMVSF_NOHDRCHK); REGISTER_ENUM(RPMVSF_NEEDPAYLOAD); REGISTER_ENUM(RPMVSF_NOSHA1HEADER); REGISTER_ENUM(RPMVSF_NOMD5HEADER); REGISTER_ENUM(RPMVSF_NODSAHEADER); REGISTER_ENUM(RPMVSF_NORSAHEADER); REGISTER_ENUM(RPMVSF_NOSHA1); REGISTER_ENUM(RPMVSF_NOMD5); REGISTER_ENUM(RPMVSF_NODSA); REGISTER_ENUM(RPMVSF_NORSA); REGISTER_ENUM(_RPMVSF_NODIGESTS); REGISTER_ENUM(_RPMVSF_NOSIGNATURES); REGISTER_ENUM(_RPMVSF_NOHEADER); REGISTER_ENUM(_RPMVSF_NOPAYLOAD); REGISTER_ENUM(TR_ADDED); REGISTER_ENUM(TR_REMOVED); REGISTER_ENUM(RPMDBI_PACKAGES); REGISTER_ENUM(RPMDBI_LABEL); REGISTER_ENUM(RPMDBI_INSTFILENAMES); REGISTER_ENUM(RPMDBI_NAME); REGISTER_ENUM(RPMDBI_BASENAMES); REGISTER_ENUM(RPMDBI_GROUP); REGISTER_ENUM(RPMDBI_REQUIRENAME); REGISTER_ENUM(RPMDBI_PROVIDENAME); REGISTER_ENUM(RPMDBI_CONFLICTNAME); REGISTER_ENUM(RPMDBI_OBSOLETENAME); REGISTER_ENUM(RPMDBI_TRIGGERNAME); REGISTER_ENUM(RPMDBI_DIRNAMES); REGISTER_ENUM(RPMDBI_INSTALLTID); REGISTER_ENUM(RPMDBI_SIGMD5); REGISTER_ENUM(RPMDBI_SHA1HEADER); REGISTER_ENUM(HEADERCONV_EXPANDFILELIST); REGISTER_ENUM(HEADERCONV_COMPRESSFILELIST); REGISTER_ENUM(HEADERCONV_RETROFIT_V3); return 1; }
static PyObject* __import__compiled(FILE *f, char *name, char *path, char *as, PyObject *local, PyObject *global) { char *module_name = as ? as : name; PyCodeObject *co; PyObject *m; if(name == NULL) return NULL; //比较文件的魔数 if(PyMarshal_ReadLongFromFile(f) != PYC_MAGIC) { PyErr_Format(PyExc_ImportError, "Bad magic number of %s", name); return NULL; } //读掉时间信息 (void*)PyMarshal_ReadLongFromFile(f); //创建PyCodeObject co = (PyCodeObject*)PyMarshal_ReadLastObjectFromFile(f); if(co == NULL) { PyErr_Format(PyExc_ImportError, "Cannot create code object from module %s", name); return NULL; } if(!PyCode_Check(co)) { PyErr_Format(PyExc_ImportError, "Non-code object in module %s", name); Py_DECREF(co); return NULL; } /*创建模块*/ m = create_module(name, (PyObject*)co); if(m == NULL) { Ps_Log("create_module failed\n", Ps_LOG_WARING); return NULL; } Py_DECREF(co); /*将模块导入命名空间*/ if(local && PyDict_Check(local)) { Py_INCREF(m); #ifdef IMPORT_DEBUG Ps_LogFormat("The module name is %s\n", Ps_LOG_NORMAL, module_name); Ps_LogObject(local, Ps_LOG_WARING); Ps_LogObject(m, Ps_LOG_WARING); int ret = #endif PyDict_SetItemString(local, module_name, m); #ifdef IMPORT_DEBUG if(ret == 0) Ps_LogFormat("ret is %d, Import module %s successfully\n", Ps_LOG_NORMAL, ret, module_name); else Ps_LogFormat("ret is %d, Import module %s failed\n", Ps_LOG_NORMAL, ret, module_name); #endif } else { PyObject *info = PyString_FromFormat("Import module %s failed", name); if(!info) { PyErr_SetString(PyExc_ImportError, "Import module failed"); } else PyErr_SetObject(PyExc_ImportError, info); return NULL; } return m; }
init_sk1objs(void) { PyObject * d, *m, *r; SKCurveType.ob_type = &PyType_Type; SKCacheType.ob_type = &PyType_Type; SKColorType.ob_type = &PyType_Type; SKFontMetricType.ob_type = &PyType_Type; SKPointType.ob_type = &PyType_Type; SKRectType.ob_type = &PyType_Type; SKTrafoType.ob_type = &PyType_Type; m = Py_InitModule("_sk1objs", curve_functions); d = PyModule_GetDict(m); /* Rect specific initialization */ /* The InfinityRect is initialized with FLT_MAX instead of HUGE_VAL now (Sketch 0.5.4), because of problems with HUGE_VAL on Alpha Linux. */ r = SKRect_FromDouble(-FLT_MAX, -FLT_MAX, FLT_MAX, FLT_MAX); if (r) { PyDict_SetItemString(d, "InfinityRect", r); SKRect_InfinityRect = (SKRectObject*)r; } r = SKRect_FromDouble(0.0, 0.0, 0.0, 0.0); if (r) { PyDict_SetItemString(d, "EmptyRect", r); SKRect_EmptyRect = (SKRectObject*)r; } /* Trafo specific initialization */ SKTrafo_ExcSingular = PyErr_NewException("_sk1objs.SingularMatrix", PyExc_ArithmeticError, NULL); if (SKTrafo_ExcSingular) { PyDict_SetItemString(d, "SingularMatrix", SKTrafo_ExcSingular); } /* Sketch type objects */ PyDict_SetItemString(d, "RectType", (PyObject*)&SKRectType); PyDict_SetItemString(d, "PointType", (PyObject*)&SKPointType); PyDict_SetItemString(d, "TrafoType", (PyObject*)&SKTrafoType); PyDict_SetItemString(d, "CurveType", (PyObject*)&SKCurveType); /* Curve specific initialization */ #define ADD_INT(name) add_int(d, name, #name) #define ADD_INT2(i, name) add_int(d, i, name) ADD_INT(ContAngle); ADD_INT(ContSmooth); ADD_INT(ContSymmetrical); ADD_INT2(CurveBezier, "Bezier"); ADD_INT2(CurveLine, "Line"); ADD_INT(SelNone); ADD_INT(SelNodes); ADD_INT(SelSegmentFirst); ADD_INT(SelSegmentLast); _SKCurve_InitCurveObject(); }
/* Convert an LDAP error into an informative python exception */ PyObject* LDAPerror( LDAP *l, char *msg ) { if (l == NULL) { PyErr_SetFromErrno( LDAPexception_class ); return NULL; } else { int errnum, opt_errnum; PyObject *errobj; PyObject *info; PyObject *str; char *matched, *error; opt_errnum = ldap_get_option(l, LDAP_OPT_ERROR_NUMBER, &errnum); if (opt_errnum != LDAP_OPT_SUCCESS) errnum = opt_errnum; if (errnum == LDAP_NO_MEMORY) return PyErr_NoMemory(); if (errnum >= LDAP_ERROR_MIN && errnum <= LDAP_ERROR_MAX) errobj = errobjects[errnum+LDAP_ERROR_OFFSET]; else errobj = LDAPexception_class; info = PyDict_New(); if (info == NULL) return NULL; str = PyString_FromString(ldap_err2string(errnum)); if (str) PyDict_SetItemString( info, "desc", str ); Py_XDECREF(str); if (ldap_get_option(l, LDAP_OPT_MATCHED_DN, &matched) >= 0 && matched != NULL) { if (*matched != '\0') { str = PyString_FromString(matched); if (str) PyDict_SetItemString( info, "matched", str ); Py_XDECREF(str); } ldap_memfree(matched); } if (errnum == LDAP_REFERRAL) { str = PyString_FromString(msg); if (str) PyDict_SetItemString( info, "info", str ); Py_XDECREF(str); } else if (ldap_get_option(l, LDAP_OPT_ERROR_STRING, &error) >= 0 && error != NULL) { if (error != '\0') { str = PyString_FromString(error); if (str) PyDict_SetItemString( info, "info", str ); Py_XDECREF(str); } ldap_memfree(error); } PyErr_SetObject( errobj, info ); Py_DECREF(info); return NULL; } }
void LDAPinit_errors( PyObject*d ) { /* create the base exception class */ LDAPexception_class = PyErr_NewException("ldap.LDAPError", NULL, NULL); PyDict_SetItemString( d, "LDAPError", LDAPexception_class ); /* XXX - backward compatibility with pre-1.8 */ PyDict_SetItemString( d, "error", LDAPexception_class ); /* create each LDAP error object */ # define seterrobj2(n,o) \ PyDict_SetItemString( d, #n, (errobjects[LDAP_##n+LDAP_ERROR_OFFSET] = o) ) # define seterrobj(n) { \ PyObject *e = PyErr_NewException("ldap." #n, \ LDAPexception_class, NULL); \ seterrobj2(n, e); \ Py_INCREF(e); \ } seterrobj(ADMINLIMIT_EXCEEDED); seterrobj(AFFECTS_MULTIPLE_DSAS); seterrobj(ALIAS_DEREF_PROBLEM); seterrobj(ALIAS_PROBLEM); seterrobj(ALREADY_EXISTS); seterrobj(AUTH_METHOD_NOT_SUPPORTED); seterrobj(AUTH_UNKNOWN); seterrobj(BUSY); seterrobj(CLIENT_LOOP); seterrobj(COMPARE_FALSE); seterrobj(COMPARE_TRUE); seterrobj(CONFIDENTIALITY_REQUIRED); seterrobj(CONNECT_ERROR); seterrobj(CONSTRAINT_VIOLATION); seterrobj(CONTROL_NOT_FOUND); seterrobj(DECODING_ERROR); seterrobj(ENCODING_ERROR); seterrobj(FILTER_ERROR); seterrobj(INAPPROPRIATE_AUTH); seterrobj(INAPPROPRIATE_MATCHING); seterrobj(INSUFFICIENT_ACCESS); seterrobj(INVALID_CREDENTIALS); seterrobj(INVALID_DN_SYNTAX); seterrobj(INVALID_SYNTAX); seterrobj(IS_LEAF); seterrobj(LOCAL_ERROR); seterrobj(LOOP_DETECT); seterrobj(MORE_RESULTS_TO_RETURN); seterrobj(NAMING_VIOLATION); seterrobj(NO_MEMORY); seterrobj(NO_OBJECT_CLASS_MODS); seterrobj(NO_OBJECT_CLASS_MODS); seterrobj(NO_RESULTS_RETURNED); seterrobj(NO_SUCH_ATTRIBUTE); seterrobj(NO_SUCH_OBJECT); seterrobj(NOT_ALLOWED_ON_NONLEAF); seterrobj(NOT_ALLOWED_ON_RDN); seterrobj(NOT_SUPPORTED); seterrobj(OBJECT_CLASS_VIOLATION); seterrobj(OPERATIONS_ERROR); seterrobj(OTHER); seterrobj(PARAM_ERROR); seterrobj(PARTIAL_RESULTS); seterrobj(PROTOCOL_ERROR); seterrobj(REFERRAL); seterrobj(REFERRAL_LIMIT_EXCEEDED); seterrobj(RESULTS_TOO_LARGE); seterrobj(SASL_BIND_IN_PROGRESS); seterrobj(SERVER_DOWN); seterrobj(SIZELIMIT_EXCEEDED); seterrobj(STRONG_AUTH_NOT_SUPPORTED); seterrobj(STRONG_AUTH_REQUIRED); seterrobj(SUCCESS); seterrobj(TIMELIMIT_EXCEEDED); seterrobj(TIMEOUT); seterrobj(TYPE_OR_VALUE_EXISTS); seterrobj(UNAVAILABLE); seterrobj(UNAVAILABLE_CRITICAL_EXTENSION); seterrobj(UNDEFINED_TYPE); seterrobj(UNWILLING_TO_PERFORM); seterrobj(USER_CANCELLED); seterrobj(VLV_ERROR); seterrobj(X_PROXY_AUTHZ_FAILURE); #ifdef LDAP_API_FEATURE_CANCEL seterrobj(CANCELLED); seterrobj(NO_SUCH_OPERATION); seterrobj(TOO_LATE); seterrobj(CANNOT_CANCEL); #endif #ifdef LDAP_ASSERTION_FAILED seterrobj(ASSERTION_FAILED); #endif #ifdef LDAP_PROXIED_AUTHORIZATION_DENIED seterrobj(PROXIED_AUTHORIZATION_DENIED); #endif }
int csl_execute(char *code, size_t size, const char *func_name, struct pack *pak, char **resptr, int *reslen) { PyObject *pCode, *pModule, *pDict, *pFunc, *pValue, *pStr; PyObject *pArgs, *pkArgs; PyMethodDef *meth; node *n; int arg_count; PyObject *argNames; pModule = PyImport_AddModule("__builtin__"); pDict = PyModule_GetDict(pModule); for (meth = methods; meth->ml_name; meth++) { pCode = PyCFunction_New(meth, NULL); PyDict_SetItemString(pDict, meth->ml_name, pCode); } if (size == 0) { n = PyParser_SimpleParseString(code, Py_file_input); if (!n) { log_exception(); return CSL_BADCODE; } pCode = (PyObject *) PyNode_Compile(n, "lala"); PyNode_Free(n); if (!pCode) { log_exception(); return CSL_BADCODE; } } else { pCode = PyMarshal_ReadObjectFromString(code, size); if (!pCode) { log_exception(); return CSL_BADCODE; } } pModule = PyImport_ExecCodeModule("csl", pCode); Py_DECREF(pCode); if (!pModule || !PyModule_Check(pModule)) { return CSL_BADCODE; } pDict = PyModule_GetDict(pModule); if (!pDict) { Py_DECREF(pModule); return CSL_BADCODE; } pFunc = PyDict_GetItemString(pDict, func_name); if (!pFunc || !PyCallable_Check(pFunc)) { Py_DECREF(pModule); return CSL_NOFUNC; } { PyObject *tempCode, *temp; tempCode = PyObject_GetAttrString(pFunc, "func_code"); temp = PyObject_GetAttrString(tempCode, "co_argcount"); arg_count = PyInt_AsLong(temp); argNames = PyObject_GetAttrString(tempCode, "co_varnames"); } pArgs = NULL; pkArgs = PyDict_New(); while (arg_count && pak) { PyObject *p; char *t, *t2; size_t sz; if (pack_get(pak, &t, &sz) == 0) break; if (pack_get(pak, &t2, &sz) == 0) { pArgs = PyTuple_New(1); PyTuple_SetItem(pArgs, 0, PyString_FromString(t)); Py_DECREF(pkArgs); break; } p = PyString_FromString(t); if (PySequence_Contains(argNames, p) == 1) { p = PyString_FromStringAndSize(t2, sz); PyDict_SetItemString(pkArgs, t, p); } } if (!pArgs) pArgs = PyTuple_New(0); pValue = PyObject_Call(pFunc, pArgs, pkArgs); if (!pValue) { log_exception(); Py_DECREF(pModule); return CSL_FUNCERR; } pStr = PyObject_Str(pValue); Py_DECREF(pValue); Py_DECREF(pModule); // is return value asked? if (resptr == NULL) return 0; *reslen = PyString_Size(pStr); *resptr = malloc((*reslen) + 1); if (!*resptr) { Py_DECREF(pStr); return CSL_NOMEM; } memcpy(*resptr, PyString_AsString(pStr), *reslen); (*resptr)[*reslen] = '\0'; return 0; }
/* Load and return the module named by 'fullname'. */ static PyObject * zipimporter_load_module(PyObject *obj, PyObject *args) { ZipImporter *self = (ZipImporter *)obj; PyObject *code = NULL, *mod, *dict; PyObject *fullname; PyObject *modpath = NULL; int ispackage; if (!PyArg_ParseTuple(args, "U:zipimporter.load_module", &fullname)) return NULL; if (PyUnicode_READY(fullname) == -1) return NULL; code = get_module_code(self, fullname, &ispackage, &modpath); if (code == NULL) goto error; mod = PyImport_AddModuleObject(fullname); if (mod == NULL) goto error; dict = PyModule_GetDict(mod); /* mod.__loader__ = self */ if (PyDict_SetItemString(dict, "__loader__", (PyObject *)self) != 0) goto error; if (ispackage) { /* add __path__ to the module *before* the code gets executed */ PyObject *pkgpath, *fullpath; PyObject *subname = get_subname(fullname); int err; fullpath = PyUnicode_FromFormat("%U%c%U%U", self->archive, SEP, self->prefix, subname); Py_DECREF(subname); if (fullpath == NULL) goto error; pkgpath = Py_BuildValue("[N]", fullpath); if (pkgpath == NULL) goto error; err = PyDict_SetItemString(dict, "__path__", pkgpath); Py_DECREF(pkgpath); if (err != 0) goto error; } mod = PyImport_ExecCodeModuleObject(fullname, code, modpath, NULL); Py_CLEAR(code); if (mod == NULL) goto error; if (Py_VerboseFlag) PySys_FormatStderr("import %U # loaded from Zip %U\n", fullname, modpath); Py_DECREF(modpath); return mod; error: Py_XDECREF(code); Py_XDECREF(modpath); return NULL; }
PyMODINIT_FUNC init_billiard(void) { PyObject *module, *temp, *value; /* Initialize module */ module = Py_InitModule("_billiard", Billiard_module_methods); if (!module) return; /* Get copy of objects from pickle */ temp = PyImport_ImportModule(PICKLE_MODULE); if (!temp) return; pickle_dumps = PyObject_GetAttrString(temp, "dumps"); pickle_loads = PyObject_GetAttrString(temp, "loads"); pickle_protocol = PyObject_GetAttrString(temp, "HIGHEST_PROTOCOL"); Py_XDECREF(temp); /* Get copy of BufferTooShort */ temp = PyImport_ImportModule("multiprocessing"); if (!temp) return; BufferTooShort = PyObject_GetAttrString(temp, "BufferTooShort"); Py_XDECREF(temp); /* Add connection type to module */ if (PyType_Ready(&BilliardConnectionType) < 0) return; Py_INCREF(&BilliardConnectionType); PyModule_AddObject(module, "Connection", (PyObject*)&BilliardConnectionType); #if defined(MS_WINDOWS) || \ (defined(HAVE_SEM_OPEN) && !defined(POSIX_SEMAPHORES_NOT_ENABLED)) /* Add SemLock type to module */ if (PyType_Ready(&BilliardSemLockType) < 0) return; Py_INCREF(&BilliardSemLockType); PyDict_SetItemString(BilliardSemLockType.tp_dict, "SEM_VALUE_MAX", Py_BuildValue("i", SEM_VALUE_MAX)); PyModule_AddObject(module, "SemLock", (PyObject*)&BilliardSemLockType); #endif #ifdef MS_WINDOWS /* Add PipeConnection to module */ if (PyType_Ready(&BilliardPipeConnectionType) < 0) return; Py_INCREF(&BilliardPipeConnectionType); PyModule_AddObject(module, "PipeConnection", (PyObject*)&BilliardPipeConnectionType); /* Initialize win32 class and add to multiprocessing */ temp = create_win32_namespace(); if (!temp) return; PyModule_AddObject(module, "win32", temp); /* Initialize the event handle used to signal Ctrl-C */ sigint_event = CreateEvent(NULL, TRUE, FALSE, NULL); if (!sigint_event) { PyErr_SetFromWindowsErr(0); return; } if (!SetConsoleCtrlHandler(ProcessingCtrlHandler, TRUE)) { PyErr_SetFromWindowsErr(0); return; } #endif /* Add configuration macros */ temp = PyDict_New(); if (!temp) return; #define ADD_FLAG(name) \ value = Py_BuildValue("i", name); \ if (value == NULL) { Py_DECREF(temp); return; } \ if (PyDict_SetItemString(temp, #name, value) < 0) { \ Py_DECREF(temp); Py_DECREF(value); return; } \ Py_DECREF(value) #if defined(HAVE_SEM_OPEN) && !defined(POSIX_SEMAPHORES_NOT_ENABLED) ADD_FLAG(HAVE_SEM_OPEN); #endif #ifdef HAVE_SEM_TIMEDWAIT ADD_FLAG(HAVE_SEM_TIMEDWAIT); #endif #ifdef HAVE_FD_TRANSFER ADD_FLAG(HAVE_FD_TRANSFER); #endif #ifdef HAVE_BROKEN_SEM_GETVALUE ADD_FLAG(HAVE_BROKEN_SEM_GETVALUE); #endif #ifdef HAVE_BROKEN_SEM_UNLINK ADD_FLAG(HAVE_BROKEN_SEM_UNLINK); #endif if (PyModule_AddObject(module, "flags", temp) < 0) return; }
// Handle the getting of a lazy attribute, ie. a native Qt signal. int qpycore_get_lazy_attr(const sipTypeDef *td, PyObject *dict) { const pyqt5QtSignal *sigs = reinterpret_cast<const pyqt5ClassPluginDef *>( sipTypePluginData(td))->qt_signals; // Handle the trvial case. if (!sigs) return 0; QByteArray default_name; qpycore_pyqtSignal *default_signal = 0; do { // See if we have come to the end of the current signal. if (default_signal && !is_signal_name(sigs->signature, default_name)) { if (PyDict_SetItemString(dict, default_name.constData(), (PyObject *)default_signal) < 0) return -1; default_signal = 0; } bool fatal; qpycore_pyqtSignal *sig = qpycore_pyqtSignal_New(sigs->signature, &fatal); if (!sig) { if (fatal) return -1; PyErr_Clear(); continue; } sig->docstring = sigs->docstring; sig->emitter = sigs->emitter; // See if this is a new default. if (default_signal) { sig->default_signal = default_signal; append_overload(sig); } else { sig->non_signals = sigs->non_signals; default_signal = sig->default_signal = sig; default_name = sigs->signature; default_name.truncate(default_name.indexOf('(')); } } while ((++sigs)->signature); // Save the last one, if any (in case of a non-fatal error). if (!default_signal) return 0; return PyDict_SetItemString(dict, default_name.constData(), (PyObject *)default_signal); }
PyMODINIT_FUNC initumath(void) #endif { PyObject *m, *d, *s, *s2, *c_api; int UFUNC_FLOATING_POINT_SUPPORT = 1; #ifdef NO_UFUNC_FLOATING_POINT_SUPPORT UFUNC_FLOATING_POINT_SUPPORT = 0; #endif /* Create the module and add the functions */ #if defined(NPY_PY3K) m = PyModule_Create(&moduledef); #else m = Py_InitModule("umath", methods); #endif if (!m) { return RETVAL; } /* Import the array */ if (_import_array() < 0) { if (!PyErr_Occurred()) { PyErr_SetString(PyExc_ImportError, "umath failed: Could not import array core."); } return RETVAL; } /* Initialize the types */ if (PyType_Ready(&PyUFunc_Type) < 0) return RETVAL; /* Add some symbolic constants to the module */ d = PyModule_GetDict(m); c_api = NpyCapsule_FromVoidPtr((void *)PyUFunc_API, NULL); if (PyErr_Occurred()) { goto err; } PyDict_SetItemString(d, "_UFUNC_API", c_api); Py_DECREF(c_api); if (PyErr_Occurred()) { goto err; } s = PyString_FromString("0.4.0"); PyDict_SetItemString(d, "__version__", s); Py_DECREF(s); /* Load the ufunc operators into the array module's namespace */ InitOperators(d); PyDict_SetItemString(d, "pi", s = PyFloat_FromDouble(NPY_PI)); Py_DECREF(s); PyDict_SetItemString(d, "e", s = PyFloat_FromDouble(NPY_E)); Py_DECREF(s); PyDict_SetItemString(d, "euler_gamma", s = PyFloat_FromDouble(NPY_EULER)); Py_DECREF(s); #define ADDCONST(str) PyModule_AddIntConstant(m, #str, UFUNC_##str) #define ADDSCONST(str) PyModule_AddStringConstant(m, "UFUNC_" #str, UFUNC_##str) ADDCONST(ERR_IGNORE); ADDCONST(ERR_WARN); ADDCONST(ERR_CALL); ADDCONST(ERR_RAISE); ADDCONST(ERR_PRINT); ADDCONST(ERR_LOG); ADDCONST(ERR_DEFAULT); ADDCONST(SHIFT_DIVIDEBYZERO); ADDCONST(SHIFT_OVERFLOW); ADDCONST(SHIFT_UNDERFLOW); ADDCONST(SHIFT_INVALID); ADDCONST(FPE_DIVIDEBYZERO); ADDCONST(FPE_OVERFLOW); ADDCONST(FPE_UNDERFLOW); ADDCONST(FPE_INVALID); ADDCONST(FLOATING_POINT_SUPPORT); ADDSCONST(PYVALS_NAME); #undef ADDCONST #undef ADDSCONST PyModule_AddIntConstant(m, "UFUNC_BUFSIZE_DEFAULT", (long)NPY_BUFSIZE); PyModule_AddObject(m, "PINF", PyFloat_FromDouble(NPY_INFINITY)); PyModule_AddObject(m, "NINF", PyFloat_FromDouble(-NPY_INFINITY)); PyModule_AddObject(m, "PZERO", PyFloat_FromDouble(NPY_PZERO)); PyModule_AddObject(m, "NZERO", PyFloat_FromDouble(NPY_NZERO)); PyModule_AddObject(m, "NAN", PyFloat_FromDouble(NPY_NAN)); #if defined(NPY_PY3K) s = PyDict_GetItemString(d, "true_divide"); PyDict_SetItemString(d, "divide", s); #endif s = PyDict_GetItemString(d, "conjugate"); s2 = PyDict_GetItemString(d, "remainder"); /* Setup the array object's numerical structures with appropriate ufuncs in d*/ PyArray_SetNumericOps(d); PyDict_SetItemString(d, "conj", s); PyDict_SetItemString(d, "mod", s2); initscalarmath(m); if (!intern_strings()) { goto err; } return RETVAL; err: /* Check for errors */ if (!PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError, "cannot load umath module."); } return RETVAL; }
/* Initializes the type object * Returns 1 if successful or -1 on error */ int pyluksde_hashing_methods_init_type( PyTypeObject *type_object ) { PyObject *value_object = NULL; if( type_object == NULL ) { return( -1 ); } type_object->tp_dict = PyDict_New(); if( type_object->tp_dict == NULL ) { return( -1 ); } #if PY_MAJOR_VERSION >= 3 value_object = PyLong_FromLong( LIBLUKSDE_HASHING_METHOD_RIPEMD160 ); #else value_object = PyInt_FromLong( LIBLUKSDE_HASHING_METHOD_RIPEMD160 ); #endif if( PyDict_SetItemString( type_object->tp_dict, "RIPEMD160", value_object ) != 0 ) { goto on_error; } #if PY_MAJOR_VERSION >= 3 value_object = PyLong_FromLong( LIBLUKSDE_HASHING_METHOD_SHA1 ); #else value_object = PyInt_FromLong( LIBLUKSDE_HASHING_METHOD_SHA1 ); #endif if( PyDict_SetItemString( type_object->tp_dict, "SHA1", value_object ) != 0 ) { goto on_error; } #if PY_MAJOR_VERSION >= 3 value_object = PyLong_FromLong( LIBLUKSDE_HASHING_METHOD_SHA256 ); #else value_object = PyInt_FromLong( LIBLUKSDE_HASHING_METHOD_SHA256 ); #endif if( PyDict_SetItemString( type_object->tp_dict, "SHA256", value_object ) != 0 ) { goto on_error; } #if PY_MAJOR_VERSION >= 3 value_object = PyLong_FromLong( LIBLUKSDE_HASHING_METHOD_SHA512 ); #else value_object = PyInt_FromLong( LIBLUKSDE_HASHING_METHOD_SHA512 ); #endif if( PyDict_SetItemString( type_object->tp_dict, "SHA512", value_object ) != 0 ) { goto on_error; } return( 1 ); on_error: if( type_object->tp_dict != NULL ) { Py_DecRef( type_object->tp_dict ); type_object->tp_dict = NULL; } return( -1 ); }
void SetItem_PyDict_AndDecref(PyObject *dict, const char* key, PyObject *value) { PyDict_SetItemString(dict, key, value); Py_DECREF(value); }
int main(int , char **) { std::string text = "1 The the DET DT _ _ 2 NMOD _ _\n" "2 Convention Convention NP NNP _ _ 4 SUB _ _\n" "3 also also ADV RB _ _ 4 VMOD _ _\n" "4 established establish V VBD _ _ _ _ _ _\n" "5 eleven eleven NOMBRE CD Numex.NUMBER _ _ _ _ _\n" "6 Working working ADJ JJ _ _ 7 NMOD _ _\n" "7 Groups group NC NNS _ _ 4 OBJ _ _\n" "8 and and CONJ CC _ _ _ _ _ _\n" "9 three three NOMBRE CD Numex.NUMBER _ _ _ _ _\n" "10 Discussion discussion NC NN _ _ 11 NMOD _ _\n" "11 Circles circle NC NNS _ _ _ DEP _ _"; /* * Find the first python executable in the path and use it as the program name. * * This allows to find the modules set up in an activated virtualenv */ QString str_program_name; QString pathEnv = QString::fromUtf8(qgetenv("PATH").constData()); QStringList paths = pathEnv.split(QRegExp("[;:]")); for (auto it = paths.begin(); it != paths.end(); ++it) { if (QFile::exists(*it + "/python" )) { str_program_name = *it + "/python"; break; } } #ifndef WIN32 Py_SetProgramName(const_cast<wchar_t*>( str_program_name.toStdWString().c_str())); #else Py_SetProgramName( (wchar_t*)str_program_name.unicode() ); #endif Py_Initialize(); PyObject* main_module = PyImport_ImportModule("__main__"); PyObject* main_dict = PyModule_GetDict(main_module); PyObject* sys_module = PyImport_ImportModule("sys"); if (sys_module == NULL) { std::cerr << "Failed to import the sys module" << std::endl; PyErr_Print(); } PyDict_SetItemString(main_dict, "sys", sys_module); // Add the path to the knowledgesrl pachkage to putho path PyObject* pythonpath = PySys_GetObject("path"); if (PyList_Append(pythonpath, PyUnicode_DecodeFSDefault("/home/gael/Projets/knowledgesrl/src")) == -1) { std::cerr << "Failed to append to python path" << std::endl; PyErr_Print(); Py_Exit(1); } // Import the semanticrolelabeler module PyObject* semanticrolelabeler_module = PyImport_ImportModule("semanticrolelabeler"); if (semanticrolelabeler_module == NULL) { std::cerr << "Failed to import srl semanticrolelabeler module" << std::endl; PyErr_Print(); Py_Exit(1); } // Create the semantic role labeller instance PyObject* instance = PyObject_CallMethod(semanticrolelabeler_module, "SemanticRoleLabeler", "[s]", "--log=debug"); if (instance == NULL) { std::cerr << "Cannot instantiate the SemanticRoleLabeler python class" << std::endl; PyErr_Print(); Py_Exit(1); } // Run the semantic role labeller PyObject* callResult = PyObject_CallMethod(instance, "annotate", "s", text.c_str()); if (callResult == NULL) { std::cerr << "Failed to call the annotate method" << std::endl; PyErr_Print(); Py_Exit(1); } // Display the SRL result const char* result = PyUnicode_AsUTF8(callResult); if (result == NULL) { std::cerr << "Cannot convert result item to string" << std::endl; PyErr_Print(); Py_Exit(1); } std::cout << "Python result is:" << std::endl << result; Py_Finalize(); return 0; }
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 ); }
// Perform any required post-initialisation. void qpycore_post_init(PyObject *module_dict) { // Add the meta-type to the module dictionary. if (PyDict_SetItemString(module_dict, "pyqtWrapperType", (PyObject *)&qpycore_pyqtWrapperType_Type) < 0) Py_FatalError("PyQt4.QtCore: Failed to set pyqtWrapperType type"); // Initialise the pyqtProperty type and add it to the module dictionary. if (PyType_Ready(&qpycore_pyqtProperty_Type) < 0) Py_FatalError("PyQt4.QtCore: Failed to initialise pyqtProperty type"); if (PyDict_SetItemString(module_dict, "pyqtProperty", (PyObject *)&qpycore_pyqtProperty_Type) < 0) Py_FatalError("PyQt4.QtCore: Failed to set pyqtProperty type"); // Initialise the pyqtSignal type and add it to the module dictionary. if (PyType_Ready(&qpycore_pyqtSignal_Type) < 0) Py_FatalError("PyQt4.QtCore: Failed to initialise pyqtSignal type"); if (PyDict_SetItemString(module_dict, "pyqtSignal", (PyObject *)&qpycore_pyqtSignal_Type) < 0) Py_FatalError("PyQt4.QtCore: Failed to set pyqtSignal type"); // Initialise the pyqtBoundSignal type and add it to the module dictionary. if (PyType_Ready(&qpycore_pyqtBoundSignal_Type) < 0) Py_FatalError("PyQt4.QtCore: Failed to initialise pyqtBoundSignal type"); if (PyDict_SetItemString(module_dict, "pyqtBoundSignal", (PyObject *)&qpycore_pyqtBoundSignal_Type) < 0) Py_FatalError("PyQt4.QtCore: Failed to set pyqtBoundSignal type"); // Initialise the private pyqtMethodProxy type. if (PyType_Ready(&qpycore_pyqtMethodProxy_Type) < 0) Py_FatalError("PyQt4.QtCore: Failed to initialise pyqtMethodProxy type"); // Register the C++ type that wraps Python objects. PyQt_PyObject::metatype = qRegisterMetaType<PyQt_PyObject>("PyQt_PyObject"); qRegisterMetaTypeStreamOperators<PyQt_PyObject>("PyQt_PyObject"); // Register the lazy attribute getter. if (sipRegisterAttributeGetter(sipType_QObject, qpycore_get_lazy_attr) < 0) Py_FatalError("PyQt4.QtCore: Failed to register attribute getter"); // Objectify some strings. #if PY_MAJOR_VERSION >= 3 qpycore_signature_attr_name = PyUnicode_FromString("__pyqtSignature__"); #else qpycore_signature_attr_name = PyString_FromString("__pyqtSignature__"); #endif if (!qpycore_signature_attr_name) Py_FatalError("PyQt4.QtCore: Failed to objectify '__pyqtSignature__'"); #if PY_MAJOR_VERSION >= 3 qpycore_name_attr_name = PyUnicode_FromString("__name__"); #else qpycore_name_attr_name = PyString_FromString("__name__"); #endif if (!qpycore_name_attr_name) Py_FatalError("PyQt4.QtCore: Failed to objectify '__name__'"); // Create the mutex that serialises access to the signal/slot proxies. We // don't use a statically initialised one because Qt needs some things to // be initialised first (at least for Windows) and this is the only way to // guarantee things are done in the right order. PyQtProxy::mutex = new QMutex(QMutex::Recursive); }
mitk::PythonService::PythonService() : m_ItkWrappingAvailable( true ), m_OpenCVWrappingAvailable( true ), m_VtkWrappingAvailable( true ), m_ErrorOccured( false ) { { MITK_DEBUG << "will init python if necessary"; } bool pythonInitialized = static_cast<bool>( Py_IsInitialized() ); //m_PythonManager.isPythonInitialized() ); { MITK_DEBUG << "pythonInitialized " << pythonInitialized; MITK_DEBUG << "m_PythonManager.isPythonInitialized() " << m_PythonManager.isPythonInitialized(); } // due to strange static var behaviour on windows Py_IsInitialized() returns correct value while // m_PythonManager.isPythonInitialized() does not because it has been constructed and destructed again if( !m_PythonManager.isPythonInitialized() ) { try { //TODO a better way to do this #ifndef WIN32 #if defined (__APPLE__) || defined(MACOSX) const char* library = "libpython2.7.dylib"; #else const char* library = "libpython2.7.so"; #endif dlerror(); if(dlopen(library, RTLD_NOW | RTLD_GLOBAL) == 0 ) { mitkThrow() << "Python runtime could not be loaded: " << dlerror(); } #endif std::string programPath = mitk::IOUtil::GetProgramPath(); QDir programmDir( QString( programPath.c_str() ).append("/Python") ); QString pythonCommand; // TODO: Check this in the modernization branch with an installer // Set the pythonpath variable depending if // we have an installer or development environment if ( programmDir.exists() ) { // runtime directory used in installers pythonCommand.append( QString("import site, sys\n") ); pythonCommand.append( QString("sys.path.append('')\n") ); pythonCommand.append( QString("sys.path.append('%1')\n").arg(programPath.c_str()) ); pythonCommand.append( QString("sys.path.append('%1/Python')").arg(programPath.c_str()) ); //pythonCommand.append( QString("\nsite.addsitedir('%1/Python/python2.7/site-packages')").arg(programPath.c_str()) ); //pythonCommand.append( QString("\nsite.addsitedir('%1/Python/python2.7/dist-packages')").arg(programPath.c_str()) ); // development } else { pythonCommand.append( QString("import site, sys\n") ); pythonCommand.append( QString("sys.path.append('')\n") ); pythonCommand.append( QString("sys.path.append('%1')\n").arg(EXTERNAL_DIST_PACKAGES) ); pythonCommand.append( QString("\nsite.addsitedir('%1')").arg(EXTERNAL_SITE_PACKAGES) ); } if( pythonInitialized ) m_PythonManager.setInitializationFlags(PythonQt::RedirectStdOut|PythonQt::PythonAlreadyInitialized); else m_PythonManager.setInitializationFlags(PythonQt::RedirectStdOut); // set python home if own runtime is used #ifdef USE_MITK_BUILTIN_PYTHON QString pythonHome; if ( programmDir.exists() ) pythonHome.append(QString("%1/Python").arg(programPath.c_str())); else pythonHome.append(PYTHONHOME); if(pHome) delete[] pHome; pHome = new char[pythonHome.toStdString().length() + 1]; strcpy(pHome,pythonHome.toStdString().c_str()); Py_SetPythonHome(pHome); MITK_DEBUG("PythonService") << "PythonHome: " << pHome; #endif MITK_DEBUG("PythonService") << "initalizing python"; m_PythonManager.initialize(); #ifdef USE_MITK_BUILTIN_PYTHON PyObject* dict = PyDict_New(); // Import builtin modules if (PyDict_GetItemString(dict, "__builtins__") == NULL) { PyObject* builtinMod = PyImport_ImportModule("__builtin__"); if (builtinMod == NULL || PyDict_SetItemString(dict, "__builtins__", builtinMod) != 0) { Py_DECREF(dict); Py_XDECREF(dict); return; } Py_DECREF(builtinMod); } #endif MITK_DEBUG("PythonService")<< "Python Search paths: " << Py_GetPath(); MITK_DEBUG("PythonService") << "python initalized"; //MITK_DEBUG("PythonService") << "registering python paths" << PYTHONPATH_COMMAND; m_PythonManager.executeString( pythonCommand, ctkAbstractPythonManager::FileInput ); } catch (...) { MITK_DEBUG("PythonService") << "exception initalizing python"; } } }
static PyObject * zipimport_zipimporter_load_module_impl(ZipImporter *self, PyObject *fullname) /*[clinic end generated code: output=7303cebf88d47953 input=c236e2e8621f04ef]*/ { PyObject *code = NULL, *mod, *dict; PyObject *modpath = NULL; int ispackage; if (PyUnicode_READY(fullname) == -1) return NULL; code = get_module_code(self, fullname, &ispackage, &modpath); if (code == NULL) goto error; mod = PyImport_AddModuleObject(fullname); if (mod == NULL) goto error; dict = PyModule_GetDict(mod); /* mod.__loader__ = self */ if (PyDict_SetItemString(dict, "__loader__", (PyObject *)self) != 0) goto error; if (ispackage) { /* add __path__ to the module *before* the code gets executed */ PyObject *pkgpath, *fullpath, *subname; int err; subname = get_subname(fullname); if (subname == NULL) goto error; fullpath = PyUnicode_FromFormat("%U%c%U%U", self->archive, SEP, self->prefix, subname); Py_DECREF(subname); if (fullpath == NULL) goto error; pkgpath = Py_BuildValue("[N]", fullpath); if (pkgpath == NULL) goto error; err = PyDict_SetItemString(dict, "__path__", pkgpath); Py_DECREF(pkgpath); if (err != 0) goto error; } mod = PyImport_ExecCodeModuleObject(fullname, code, modpath, NULL); Py_CLEAR(code); if (mod == NULL) goto error; if (Py_VerboseFlag) PySys_FormatStderr("import %U # loaded from Zip %U\n", fullname, modpath); Py_DECREF(modpath); return mod; error: Py_XDECREF(code); Py_XDECREF(modpath); return NULL; }
void embed_sim_init(gpi_sim_info_t *info) { FENTER int i; /* Check that we are not already initialised */ if (pEventFn) return; // Find the simulation root gpi_sim_hdl dut = gpi_get_root_handle(getenv("TOPLEVEL")); if (dut == NULL) { fprintf(stderr, "Unable to find root instance!\n"); gpi_sim_end(); return; } PyObject *cocotb_module, *cocotb_init, *cocotb_args, *cocotb_retval; PyObject *simlog_obj, *simlog_func; PyObject *argv_list, *argc, *arg_dict, *arg_value; cocotb_module = NULL; arg_dict = NULL; //Ensure that the current thread is ready to callthe Python C API PyGILState_STATE gstate = PyGILState_Ensure(); if (get_module_ref(COCOTB_MODULE, &cocotb_module)) goto cleanup; // Create a logger object simlog_obj = PyObject_GetAttrString(cocotb_module, "log"); if (simlog_obj == NULL) { PyErr_Print(); fprintf(stderr, "Failed to to get simlog object\n"); } simlog_func = PyObject_GetAttrString(simlog_obj, "_printRecord"); if (simlog_func == NULL) { PyErr_Print(); fprintf(stderr, "Failed to get the _printRecord method"); goto cleanup; } if (!PyCallable_Check(simlog_func)) { PyErr_Print(); fprintf(stderr, "_printRecord is not callable"); goto cleanup; } set_log_handler(simlog_func); Py_DECREF(simlog_func); 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); }
void pygst_exceptions_register_classes (PyObject * d) { PyObject *dict = NULL; /* register gst.LinkError */ dict = PyDict_New (); if (dict == NULL) goto exception; PyGstExc_LinkError = PyErr_NewException ("gst.LinkError", PyExc_Exception, dict); if (PyGstExc_LinkError == NULL) goto exception; if (add_method (PyGstExc_LinkError, dict, &link_error_init_method) < 0) goto exception; Py_DECREF (dict); if (PyDict_SetItemString (d, "LinkError", PyGstExc_LinkError) < 0) goto exception; Py_DECREF (PyGstExc_LinkError); /* register gst.AddError */ PyGstExc_AddError = PyErr_NewException ("gst.AddError", PyExc_Exception, NULL); if (PyGstExc_AddError == NULL) goto exception; if (PyDict_SetItemString (d, "AddError", PyGstExc_AddError) < 0) goto exception; Py_DECREF (PyGstExc_AddError); /* register gst.RemoveError */ PyGstExc_RemoveError = PyErr_NewException ("gst.RemoveError", PyExc_Exception, NULL); if (PyGstExc_RemoveError == NULL) goto exception; if (PyDict_SetItemString (d, "RemoveError", PyGstExc_RemoveError) < 0) goto exception; Py_DECREF (PyGstExc_RemoveError); /* register gst.QueryError */ PyGstExc_QueryError = PyErr_NewException ("gst.QueryError", PyExc_Exception, NULL); if (PyGstExc_QueryError == NULL) goto exception; if (PyDict_SetItemString (d, "QueryError", PyGstExc_QueryError) < 0) goto exception; Py_DECREF (PyGstExc_QueryError); /* FIXME: remove this method in 0.11; element_factory_make deals with element factories, not plug-ins */ /* register gst.PluginNotFoundError */ dict = PyDict_New (); if (dict == NULL) goto exception; PyGstExc_PluginNotFoundError = PyErr_NewException ("gst.PluginNotFoundError", PyExc_Exception, dict); if (PyGstExc_PluginNotFoundError == NULL) goto exception; if (add_method (PyGstExc_PluginNotFoundError, dict, &element_not_found_error_init_method) < 0) goto exception; Py_DECREF (dict); if (PyDict_SetItemString (d, "PluginNotFoundError", PyGstExc_PluginNotFoundError) < 0) goto exception; Py_DECREF (PyGstExc_PluginNotFoundError); /* register gst.ElementNotFoundError */ dict = PyDict_New (); if (dict == NULL) goto exception; PyGstExc_ElementNotFoundError = PyErr_NewException ("gst.ElementNotFoundError", PyGstExc_PluginNotFoundError, dict); if (PyGstExc_ElementNotFoundError == NULL) goto exception; if (add_method (PyGstExc_ElementNotFoundError, dict, &element_not_found_error_init_method) < 0) goto exception; Py_DECREF (dict); if (PyDict_SetItemString (d, "ElementNotFoundError", PyGstExc_ElementNotFoundError) < 0) goto exception; Py_DECREF (PyGstExc_ElementNotFoundError); return; return; exception: Py_XDECREF (dict); Py_XDECREF (PyGstExc_LinkError); Py_XDECREF (PyGstExc_AddError); Py_XDECREF (PyGstExc_RemoveError); Py_XDECREF (PyGstExc_QueryError); Py_XDECREF (PyGstExc_PluginNotFoundError); Py_XDECREF (PyGstExc_ElementNotFoundError); return; }
static PyObject * read_objects(PyObject * self, PyObject * args) { SHPHandle hSHP; PyObject * cobject; char * shape_name; if (!PyArg_ParseTuple(args, "O!s", &PyCObject_Type, &cobject, &shape_name)) return NULL; hSHP = PyCObject_AsVoidPtr(cobject); // check if already in memory if (map_dict != NULL) { PyObject * result = PyDict_GetItemString(map_dict, shape_name); if (result != NULL) return result; } int nEntities; int nShapeType; SHPGetInfo(hSHP, &nEntities, &nShapeType, NULL, NULL); PyObject * list = NULL, * parts = NULL, * point = NULL, *vertices = NULL, *px = NULL, *py = NULL; SHPObject * psCShape; int i,j,k,s,count,numPoints; 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) { // read points from shp file numPoints = psCShape->nVertices; for (j=0; j < numPoints; j++) { x = psCShape->padfX[j]; y = psCShape->padfY[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(list, i, point); } } 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++) { if ( j < psCShape->nParts - 1) numPoints = psCShape->panPartStart[j+1] - psCShape->panPartStart[j]; else numPoints = psCShape->nVertices - psCShape->panPartStart[j]; s = psCShape->panPartStart[j]; vertices = PyList_New(numPoints); for (k=0; k < numPoints; k++) { x = psCShape->padfX[s+k]; y = psCShape->padfY[s+k]; px = PyFloat_FromDouble(x); py = PyFloat_FromDouble(y); point = PyTuple_New(2); PyTuple_SetItem(point, 0, px); PyTuple_SetItem(point, 1, py); PyList_SetItem(vertices, k, point); } PyList_SetItem(parts,j,vertices); } PyList_SetItem(list, i, parts); } SHPDestroyObject(psCShape); } // store the list if (map_dict == NULL) { map_dict = PyDict_New(); } PyDict_SetItemString(map_dict, shape_name, list); //Py_DECREF(list); return list; }
/* Initializes the type object * Returns 1 if successful or -1 on error */ int pyewf_media_types_init_type( PyTypeObject *type_object ) { PyObject *value_object = NULL; if( type_object == NULL ) { return( -1 ); } type_object->tp_dict = PyDict_New(); if( type_object->tp_dict == NULL ) { return( -1 ); } #if PY_MAJOR_VERSION >= 3 value_object = PyLong_FromLong( LIBEWF_MEDIA_TYPE_REMOVABLE ); #else value_object = PyInt_FromLong( LIBEWF_MEDIA_TYPE_REMOVABLE ); #endif if( PyDict_SetItemString( type_object->tp_dict, "REMOVABLE", value_object ) != 0 ) { goto on_error; } #if PY_MAJOR_VERSION >= 3 value_object = PyLong_FromLong( LIBEWF_MEDIA_TYPE_FIXED ); #else value_object = PyInt_FromLong( LIBEWF_MEDIA_TYPE_FIXED ); #endif if( PyDict_SetItemString( type_object->tp_dict, "FIXED", value_object ) != 0 ) { goto on_error; } #if PY_MAJOR_VERSION >= 3 value_object = PyLong_FromLong( LIBEWF_MEDIA_TYPE_OPTICAL ); #else value_object = PyInt_FromLong( LIBEWF_MEDIA_TYPE_OPTICAL ); #endif if( PyDict_SetItemString( type_object->tp_dict, "OPTICAL", value_object ) != 0 ) { goto on_error; } #if PY_MAJOR_VERSION >= 3 value_object = PyLong_FromLong( LIBEWF_MEDIA_TYPE_SINGLE_FILES ); #else value_object = PyInt_FromLong( LIBEWF_MEDIA_TYPE_SINGLE_FILES ); #endif if( PyDict_SetItemString( type_object->tp_dict, "SINGLE_FILES", value_object ) != 0 ) { goto on_error; } #if PY_MAJOR_VERSION >= 3 value_object = PyLong_FromLong( LIBEWF_MEDIA_TYPE_MEMORY ); #else value_object = PyInt_FromLong( LIBEWF_MEDIA_TYPE_MEMORY ); #endif if( PyDict_SetItemString( type_object->tp_dict, "MEMORY", value_object ) != 0 ) { goto on_error; } return( 1 ); on_error: if( type_object->tp_dict != NULL ) { Py_DecRef( type_object->tp_dict ); type_object->tp_dict = NULL; } return( -1 ); }