コード例 #1
0
ファイル: pydcext.c プロジェクト: svn2github/dyncall
static PyObject*
pydc_call(PyObject* self, PyObject* in_args)
{
  PyObject*   pcobj_funcptr;
  const char* signature;
  PyObject*   args;
  int         l;
  const char* ptr;
  char        ch;
  int         pos;
  void*       pfunc;
  
  if ( !PyArg_ParseTuple(in_args,"OsO", &pcobj_funcptr, &signature, &args) ) return PyErr_Format(PyExc_RuntimeError, "argument mismatch");
  pfunc = PyCObject_AsVoidPtr(pcobj_funcptr);  
  if ( !pfunc ) return PyErr_Format( PyExc_RuntimeError, "function pointer is NULL" );
  l = PyTuple_Size(args);

  ptr = signature;
  pos = 0; 

  dcReset(gpCall);
  
  while ( (ch = *ptr) != '\0' && ch != ')' ) 
  {
    PyObject* po;

    int index = pos+1;

    if (pos > l) return PyErr_Format( PyExc_RuntimeError, "expecting more arguments" );

    po = PyTuple_GetItem(args,pos);

    switch(ch) 
    {
      case DC_SIGCHAR_BOOL:
      {
        DCbool b;
        if ( !PyBool_Check(po) ) return PyErr_Format( PyExc_RuntimeError, "argument mismatch at pos %d - expecting a bool", index ); 
        b = (Py_True == po) ? DC_TRUE : DC_FALSE;
        dcArgBool(gpCall, b);
      }
      break;
      case DC_SIGCHAR_CHAR:
      {
        DCchar c;
        if ( PyString_Check(po) )
        {
          // Py_ssize_t l;
          size_t l;
          char* s;
          l = PyString_GET_SIZE(po);
          if (l != 1) return PyErr_Format( PyExc_RuntimeError, "argument mismatch at pos %d - expecting a string with length of 1 (a char string)", index );          
          s = PyString_AsString(po);          
          c = (DCchar) s[0];
        }
        else if ( PyInt_Check(po) ) 
        {
          long l;
          l = PyInt_AsLong(po);
          if ( (l > CHAR_MAX) || (l < CHAR_MIN)) return PyErr_Format( PyExc_RuntimeError, "value out of range at argument %d - expecting a char code", index );
          c = (DCchar) l;
        }
        else return PyErr_Format( PyExc_RuntimeError, "argument mismatch at pos %d - expecting a char", index );        
        dcArgChar(gpCall, c);
      }
      break;
      case DC_SIGCHAR_SHORT:
      {
        DCshort s;
        long v;
        if ( !PyInt_Check(po) )
          return PyErr_Format( PyExc_RuntimeError, "argument mismatch at pos %d - expecting a short int", index ); 
        v = PyInt_AS_LONG(po);
        if ( (v < SHRT_MIN) || (v > SHRT_MAX) ) 
          return PyErr_Format( PyExc_RuntimeError, "value out of range at argument %d - expecting a short value", index );
        s = (DCshort) v;
        dcArgShort(gpCall, s);
      } 
      break;
      case DC_SIGCHAR_INT:
      {
        long v;
        if ( !PyInt_Check(po) ) return PyErr_Format( PyExc_RuntimeError, "argument mismatch at pos %d - expecting an int", index ); 
        v = PyInt_AS_LONG(po);
        dcArgInt(gpCall, (DCint) v );
      }
      break;
      case DC_SIGCHAR_LONG:
      {
        long v;
        if ( !PyInt_Check(po) ) return PyErr_Format( PyExc_RuntimeError, "argument mismatch at pos %d - expecting an int", index ); 
        v = PyInt_AsLong(po);
        
      }
      break;
      case DC_SIGCHAR_LONGLONG:
      {
        PY_LONG_LONG pl;
        DClonglong dl;
        if ( !PyLong_Check(po) ) return PyErr_Format( PyExc_RuntimeError, "argument mismatch at pos %d - expecting a long long", index );
        pl = PyLong_AsLongLong(po);
        dl = (DClonglong) pl;
        dcArgLongLong(gpCall, dl );
      }
      break;
      case DC_SIGCHAR_FLOAT:
      {
        DCfloat f;
        if (!PyFloat_Check(po)) return PyErr_Format( PyExc_RuntimeError, "argument mismatch at pos %d - expeecting a float", index );
        f = (float) PyFloat_AsDouble(po);
        dcArgFloat(gpCall, f);
      }
      break;
      case DC_SIGCHAR_DOUBLE:
      {
        double d;
        if (!PyFloat_Check(po)) return PyErr_Format( PyExc_RuntimeError, "argument mismatch at pos %d - expeecting a float", index );
        d = PyFloat_AsDouble(po);
        dcArgDouble(gpCall, d);      
      }
      break;
      case DC_SIGCHAR_POINTER:
      {
        DCpointer ptr;
        if ( PyString_Check(po) ) {
          ptr = (DCpointer) PyString_AsString(po);
        } else if ( PyLong_Check(po) ) {
          ptr = (DCpointer) ( (DCint) PyLong_AsLongLong(po) );
        } else {
          return PyErr_Format( PyExc_RuntimeError, "argument mismatch at pos %d - expecting a promoting pointer-type (int,string)", index );
        }
        dcArgPointer(gpCall, ptr );
      }
      break;
      case 'S':
      {
        char* p;
        if (!PyString_Check(po) ) return PyErr_Format( PyExc_RuntimeError, "argument mismatch at pos %d - expecting a string", index );
        p = PyString_AsString(po);
        dcArgPointer(gpCall, (DCpointer) p );
      }
      break;
      default: return PyErr_Format( PyExc_RuntimeError, "unknown signature character '%c'", ch);
    }

    ++pos; ++ptr;

  }

  if (pos != l) return PyErr_Format( PyExc_RuntimeError, "too many arguments");

  if (ch == '\0') return PyErr_Format( PyExc_RuntimeError, "return value missing in signature");

  ch = *++ptr;

  switch(ch) 
  {
    case DC_SIGCHAR_VOID: dcCallVoid(gpCall, pfunc); Py_RETURN_NONE;
    case DC_SIGCHAR_BOOL: return Py_BuildValue("i", dcCallBool(gpCall, pfunc) );
    case DC_SIGCHAR_INT: return Py_BuildValue("i", dcCallInt(gpCall, pfunc) ); 
    case DC_SIGCHAR_LONGLONG: return Py_BuildValue("L", (unsigned long long) dcCallLongLong(gpCall, pfunc) );
    case DC_SIGCHAR_FLOAT: return Py_BuildValue("f", dcCallFloat(gpCall, pfunc) ); 
    case DC_SIGCHAR_DOUBLE: return Py_BuildValue("d", dcCallDouble(gpCall, pfunc) ); 
    case 's': return Py_BuildValue("s", dcCallPointer(gpCall, pfunc) ); 
    case DC_SIGCHAR_POINTER: return Py_BuildValue("p", dcCallPointer(gpCall, pfunc) ); 
    default:  return PyErr_Format( PyExc_RuntimeError, "invalid return type signature" );
  }
}
コード例 #2
0
ファイル: snmp.c プロジェクト: arielsalvo/wiremaps
static PyObject*
Snmp_op(SnmpObject *self, PyObject *args, int op)
{
	PyObject *roid, *oids, *item, *deferred = NULL, *req = NULL;
	char *aoid, *next;
	oid poid[MAX_OID_LEN];
	struct snmp_pdu *pdu=NULL;
	int maxrepetitions = 10, norepeaters = 0;
	int i, oidlen, reqid;
	size_t arglen;

	if (op == SNMP_MSG_GETBULK) {
		if (!PyArg_ParseTuple(args, "O|ii",
			&roid, &maxrepetitions, &norepeaters))
			return NULL;
	} else {
		if (!PyArg_ParseTuple(args, "O", &roid))
			return NULL;
	}

	/* Turn the first argument into a tuple */
	if (!PyTuple_Check(roid) && !PyList_Check(roid) && !PyString_Check(roid)) {
		PyErr_SetString(PyExc_TypeError,
		    "argument should be a string, a list or a tuple");
		return NULL;
	}
	if (PyString_Check(roid)) {
		if ((oids = PyTuple_Pack(1, roid)) == NULL)
			return NULL;
	} else if (PyList_Check(roid)) {
		if ((oids = PyList_AsTuple(roid)) == NULL)
			return NULL;
	} else {
		oids = roid;
		Py_INCREF(oids);
	}
	
	Py_INCREF(self);
	arglen = PyTuple_Size(oids);
	pdu = snmp_pdu_create(op);
	if (op == SNMP_MSG_GETBULK) {
		pdu->max_repetitions = maxrepetitions;
		pdu->non_repeaters = norepeaters;
	}
	for (i = 0; i < arglen; i++) {
		if ((item = PyTuple_GetItem(oids, i)) == NULL)
			goto operror;
		if (!PyString_Check(item)) {
			PyErr_Format(PyExc_TypeError,
			    "element %d should be a string", i);
			goto operror;
		}
		aoid = PyString_AsString(item);
		oidlen = 0;
		while (aoid && (*aoid != '\0')) {
			if (aoid[0] == '.')
				aoid++;
			if (oidlen >= MAX_OID_LEN) {
				PyErr_Format(PyExc_ValueError,
				    "element %d is too large for OID", i);
				goto operror;
			}
			poid[oidlen++] = strtoull(aoid, &next, 10);
			if (aoid == next) {
				PyErr_Format(PyExc_TypeError,
				    "element %d is not a valid OID: %s", i, aoid);
				goto operror;
			}
			aoid = next;
		}
		snmp_add_null_var(pdu, poid, oidlen);
	}
	self->ss->callback = Snmp_handle;
	self->ss->callback_magic = self;
	if ((deferred = PyObject_CallMethod(DeferModule,
		    "Deferred", NULL)) == NULL)
		goto operror;
	if (!snmp_send(self->ss, pdu)) {
		Snmp_raise_error(self->ss);
		/* Instead of raising, we will fire errback */
		Snmp_invokeerrback(deferred);
		Py_DECREF(self);
		Py_DECREF(oids);
		snmp_free_pdu(pdu);
		return deferred;
	}
	reqid = pdu->reqid;
	pdu = NULL;		/* Avoid to free it when future errors occurs */

	/* We create a Deferred object and put it in a dictionary using
	 * pdu->reqid to be able to call its callbacks later. */
	if ((req = PyInt_FromLong(reqid)) == NULL)
		goto operror;
	if (PyDict_SetItem(self->defers, req, deferred) != 0) {
		Py_DECREF(req);
		goto operror;
	}
	Py_DECREF(req);
	if (Snmp_updatereactor() == -1)
		goto operror;
	Py_DECREF(oids);
	return deferred;
	
operror:
	Py_XDECREF(deferred);
	Py_DECREF(self);
	Py_DECREF(oids);
	snmp_free_pdu(pdu);
	return NULL;
}
コード例 #3
0
AerospikeQuery * AerospikeQuery_Select(AerospikeQuery * self, PyObject * args, PyObject * kwds)
{
	TRACE();

	int nbins = (int) PyTuple_Size(args);
	char * bin = NULL;
	PyObject * py_ubin = NULL;
	as_error err;
	as_error_init(&err);

	if (!self || !self->client->as) {
		as_error_update(&err, AEROSPIKE_ERR_PARAM, "Invalid aerospike object");
		goto CLEANUP;
	}

	if (!self->client->is_conn_16) {
		as_error_update(&err, AEROSPIKE_ERR_CLUSTER, "No connection to aerospike cluster");
		goto CLEANUP;
	}

	as_query_select_init(&self->query, nbins);

	for ( int i = 0; i < nbins; i++ ) {
		PyObject * py_bin = PyTuple_GetItem(args, i);
		if (PyUnicode_Check(py_bin)){
			py_ubin = PyUnicode_AsUTF8String(py_bin);
			bin = PyString_AsString(py_ubin);
		}
		else if (PyString_Check(py_bin)) {
			// TRACE();
			bin = PyString_AsString(py_bin);
		} else {
			// TRACE();
			as_error_update(&err, AEROSPIKE_ERR_PARAM, "Bin name should be of type string");
			PyObject * py_err = NULL;
			error_to_pyobject(&err, &py_err);
			PyObject *exception_type = raise_exception(&err);
			PyErr_SetObject(exception_type, py_err);
			Py_DECREF(py_err);
			return NULL;
		}

		as_query_select(&self->query, bin);

		if (py_ubin){
			Py_DECREF(py_ubin);
			py_ubin = NULL;
		}
	}

CLEANUP:
	if ( err.code != AEROSPIKE_OK ) {
		PyObject * py_err = NULL;
		error_to_pyobject(&err, &py_err);
		PyObject *exception_type = raise_exception(&err);
		PyErr_SetObject(exception_type, py_err);
		Py_DECREF(py_err);
		return NULL;
	}

	Py_INCREF(self);
	return self;
}
コード例 #4
0
static void initialize_bin_for_strictypes(AerospikeClient *self, as_error *err, PyObject *py_value, as_binop *binop, char *bin, as_static_pool *static_pool) {
	
	as_bin *binop_bin = &binop->bin;
	if (PyInt_Check(py_value)) {
		int val = PyInt_AsLong(py_value);
		as_integer_init((as_integer *) &binop_bin->value, val);
		binop_bin->valuep = &binop_bin->value;
	} else if (PyLong_Check(py_value)) {
		long val = PyLong_AsLong(py_value);
		as_integer_init((as_integer *) &binop_bin->value, val);
		binop_bin->valuep = &binop_bin->value;
	} else if (PyString_Check(py_value)) {
		char * val = PyString_AsString(py_value);
		as_string_init((as_string *) &binop_bin->value, val, false);
		binop_bin->valuep = &binop_bin->value;	
	} else if (PyUnicode_Check(py_value)) {
		PyObject *py_ustr1 = PyUnicode_AsUTF8String(py_value);
		char * val = PyString_AsString(py_ustr1);
		as_string_init((as_string *) &binop_bin->value, val, false);
		binop_bin->valuep = &binop_bin->value;	
	} else if (PyFloat_Check(py_value)) {
		int64_t val = PyFloat_AsDouble(py_value);
		if (aerospike_has_double(self->as)) {
			as_double_init((as_double *) &binop_bin->value, val);
			binop_bin->valuep = &binop_bin->value;
		} else {
			as_bytes *bytes;
			GET_BYTES_POOL(bytes, static_pool, err);
			serialize_based_on_serializer_policy(self, SERIALIZER_PYTHON, &bytes, py_value, err);	
			((as_val *) &binop_bin->value)->type = AS_UNKNOWN;
			binop_bin->valuep = (as_bin_value *) bytes;
		}
	} else if (PyList_Check(py_value)) {
		as_list * list = NULL;
		pyobject_to_list(self, err, py_value, &list, static_pool, SERIALIZER_PYTHON);
		((as_val *) &binop_bin->value)->type = AS_UNKNOWN;
		binop_bin->valuep = (as_bin_value *) list;
	} else if (PyDict_Check(py_value)) {
		as_map * map = NULL;
		pyobject_to_map(self, err, py_value, &map, static_pool, SERIALIZER_PYTHON);
		((as_val *) &binop_bin->value)->type = AS_UNKNOWN;
		binop_bin->valuep = (as_bin_value *) map;
	} else if (!strcmp(py_value->ob_type->tp_name, "aerospike.Geospatial")) {
		PyObject* py_data = PyObject_GenericGetAttr(py_value, PyString_FromString("geo_data"));
		char *geo_value = PyString_AsString(AerospikeGeospatial_DoDumps(py_data, err));
		if (aerospike_has_geo(self->as)) {
			as_geojson_init((as_geojson *) &binop_bin->value, geo_value, false);
			binop_bin->valuep = &binop_bin->value;
		} else {
			as_bytes *bytes;
			GET_BYTES_POOL(bytes, static_pool, err);
			serialize_based_on_serializer_policy(self, SERIALIZER_PYTHON, &bytes, py_data, err);	
			((as_val *) &binop_bin->value)->type = AS_UNKNOWN;
			binop_bin->valuep = (as_bin_value *) bytes;
		}
	} else if (!strcmp(py_value->ob_type->tp_name, "aerospike.null")) {
		((as_val *) &binop_bin->value)->type = AS_UNKNOWN;
		binop_bin->valuep = (as_bin_value *) &as_nil;
	} else if (PyByteArray_Check(py_value)) {
		as_bytes *bytes;
		GET_BYTES_POOL(bytes, static_pool, err);
		serialize_based_on_serializer_policy(self, SERIALIZER_PYTHON, &bytes, py_value, err);
		as_bytes_init_wrap((as_bytes *) &binop_bin->value, bytes->value, bytes->size, false);	
		binop_bin->valuep = &binop_bin->value;
	} else {
		as_bytes *bytes;
		GET_BYTES_POOL(bytes, static_pool, err);
		serialize_based_on_serializer_policy(self, SERIALIZER_PYTHON, &bytes, py_value, err);	
		((as_val *) &binop_bin->value)->type = AS_UNKNOWN;
		binop_bin->valuep = (as_bin_value *) bytes;
	}
	strcpy(binop_bin->name, bin);
}
コード例 #5
0
static enum string_repr_result
print_string_repr (PyObject *printer, const char *hint,
		   struct ui_file *stream, int recurse,
		   const struct value_print_options *options,
		   const struct language_defn *language,
		   struct gdbarch *gdbarch)
{
  struct value *replacement = NULL;
  enum string_repr_result result = string_repr_ok;

  gdbpy_ref<> py_str (pretty_print_one_value (printer, &replacement));
  if (py_str != NULL)
    {
      if (py_str == Py_None)
	result = string_repr_none;
      else if (gdbpy_is_lazy_string (py_str.get ()))
	{
	  CORE_ADDR addr;
	  long length;
	  struct type *type;
	  gdb::unique_xmalloc_ptr<char> encoding;
	  struct value_print_options local_opts = *options;

	  gdbpy_extract_lazy_string (py_str.get (), &addr, &type,
				     &length, &encoding);

	  local_opts.addressprint = 0;
	  val_print_string (type, encoding.get (), addr, (int) length,
			    stream, &local_opts);
	}
      else
	{
	  gdbpy_ref<> string
	    (python_string_to_target_python_string (py_str.get ()));
	  if (string != NULL)
	    {
	      char *output;
	      long length;
	      struct type *type;

#ifdef IS_PY3K
	      output = PyBytes_AS_STRING (string.get ());
	      length = PyBytes_GET_SIZE (string.get ());
#else
	      output = PyString_AsString (string.get ());
	      length = PyString_Size (string.get ());
#endif
	      type = builtin_type (gdbarch)->builtin_char;

	      if (hint && !strcmp (hint, "string"))
		LA_PRINT_STRING (stream, type, (gdb_byte *) output,
				 length, NULL, 0, options);
	      else
		fputs_filtered (output, stream);
	    }
	  else
	    {
	      result = string_repr_error;
	      print_stack_unless_memory_error (stream);
	    }
	}
    }
  else if (replacement)
    {
      struct value_print_options opts = *options;

      opts.addressprint = 0;
      common_val_print (replacement, stream, recurse, &opts, language);
    }
  else
    {
      result = string_repr_error;
      print_stack_unless_memory_error (stream);
    }

  return result;
}
コード例 #6
0
// Here we actually print
static PyObject *Printer_print(Printer *self)
{
	if (!ScCore->primaryMainWindow()->HaveDoc) {
		PyErr_SetString(PyExc_SystemError, "Need to open documetnt first");
		return NULL;
	}
// copied from void ScribusMainWindow::slotFilePrint() in file scribus.cpp
	QString fna, prn, cmd, scmd, cc, data, SepName;
	QString printcomm;
	bool fil, PSfile;
	PSfile = false;

//    ReOrderText(ScCore->primaryMainWindow()->doc, ScCore->primaryMainWindow()->view);
	prn = QString(PyString_AsString(self->printer));
	fna = QString(PyString_AsString(self->file));
	fil = (QString(PyString_AsString(self->printer)) == QString("File")) ? true : false;
	std::vector<int> pageNs;
	PrintOptions options;
	for (int i = 0; i < PyList_Size(self->pages); ++i) {
		options.pageNumbers.push_back((int)PyInt_AsLong(PyList_GetItem(self->pages, i)));
	}
	int Nr = (self->copies < 1) ? 1 : self->copies;
	SepName = QString(PyString_AsString(self->separation));
	options.printer   = prn;
	options.prnEngine = (PrintEngine) self->pslevel;
	options.toFile    = fil;
	options.separationName = SepName;
	options.outputSeparations = (SepName == QString("No")) ?  false : true;
	options.useColor = self->color;
	options.mirrorH  = self->mph;
	options.mirrorV  = self->mpv;
	options.useICC   = self->useICC;
	options.doGCR    = self->ucr;
	options.cropMarks  = false;
	options.bleedMarks = false;
	options.registrationMarks = false;
	options.colorMarks = false;
	options.markOffset = 0.0;
	options.bleeds.Top    = 0.0;
	options.bleeds.Left   = 0.0;
	options.bleeds.Right  = 0.0;
	options.bleeds.Bottom = 0.0;
	if (!PrinterUtil::checkPrintEngineSupport(options.printer, options.prnEngine, options.toFile))
		options.prnEngine = PrinterUtil::getDefaultPrintEngine(options.printer, options.toFile);
	printcomm = QString(PyString_AsString(self->cmd));
	QMap<QString, QMap<uint, FPointArray> > ReallyUsed;
	ReallyUsed.clear();
	ScCore->primaryMainWindow()->doc->getUsedFonts(ReallyUsed);
	PrefsManager *prefsManager=PrefsManager::instance();

#if defined(_WIN32)
	if (!options.toFile)
	{
		QByteArray devMode;
		bool printDone = false;
		if ( PrinterUtil::getDefaultSettings(prn, options.devMode) )
		{
			ScPrintEngine_GDI winPrint;
			printDone = winPrint.print( *ScCore->primaryMainWindow()->doc, options );
		}
		if (!printDone)
			PyErr_SetString(PyExc_SystemError, "Printing failed");
		Py_RETURN_NONE;
	}
#endif

	PSLib *dd = new PSLib(options, true, prefsManager->appPrefs.AvailFonts, ReallyUsed, ScCore->primaryMainWindow()->doc->PageColors, false, true);
	if (dd != NULL)
	{
		if (!fil)
			fna = QDir::convertSeparators(ScPaths::getTempFileDir()+"/tmp.ps");
		PSfile = dd->PS_set_file(fna);
		fna = QDir::convertSeparators(fna);
		if (PSfile)
		{
			options.setDevParam = false;
			options.doClip = false;
			dd->CreatePS(ScCore->primaryMainWindow()->doc, options);
			if (options.prnEngine == PostScript1 || options.prnEngine == PostScript2)
			{
				if (ScCore->haveGS())
				{
					QString tmp;
					QStringList opts;
					opts.append( QString("-dDEVICEWIDTHPOINTS=%1").arg(tmp.setNum(ScCore->primaryMainWindow()->doc->pageWidth)) );
					opts.append( QString("-dDEVICEHEIGHTPOINTS=%1").arg(tmp.setNum(ScCore->primaryMainWindow()->doc->pageHeight)) );
					convertPS2PS(fna, fna+".tmp", opts, options.prnEngine);
					moveFile( fna + ".tmp", fna );
				}
				else
				{
					PyErr_SetString(PyExc_SystemError, "Printing failed : GhostScript is needed to print to PostScript Level 1 or Level 2");
					Py_RETURN_NONE;
				}
			}

			if (!fil)
			{
				if (!printcomm.isEmpty())
					cmd = printcomm + " "+fna;
				else
				{
					cmd = "lpr -P" + prn;
					if (Nr > 1)
						cmd += " -#" + cc.setNum(Nr);
#ifdef HAVE_CUPS
// This need yet to be implemented by object Printer
//					cmd += printer->PrinterOpts;
#endif
					cmd += " "+fna;
				}
				system(cmd.toLocal8Bit().constData());
				unlink(fna.toLocal8Bit().constData());
			}
		}
		else {
			delete dd;
			PyErr_SetString(PyExc_SystemError, "Printing failed");
			return NULL;
		}
		delete dd;
	}
//	Py_INCREF(Py_None);
//	return Py_None;
	Py_RETURN_NONE;
}
コード例 #7
0
ファイル: XBPyThread.cpp プロジェクト: AWilco/xbmc
void XBPyThread::Process()
{
  CLog::Log(LOGDEBUG,"Python thread: start processing");

  int m_Py_file_input = Py_file_input;

  // get the global lock
  PyEval_AcquireLock();
  PyThreadState* state = Py_NewInterpreter();
  if (!state)
  {
    PyEval_ReleaseLock();
    CLog::Log(LOGERROR,"Python thread: FAILED to get thread state!");
    return;
  }
  // swap in my thread state
  PyThreadState_Swap(state);

  m_pExecuter->InitializeInterpreter(addon);

  CLog::Log(LOGDEBUG, "%s - The source file to load is %s", __FUNCTION__, m_source);

  // get path from script file name and add python path's
  // this is used for python so it will search modules from script path first
  CStdString scriptDir;
  URIUtils::GetDirectory(_P(m_source), scriptDir);
  URIUtils::RemoveSlashAtEnd(scriptDir);
  CStdString path = scriptDir;

  // add on any addon modules the user has installed
  ADDON::VECADDONS addons;
  ADDON::CAddonMgr::Get().GetAddons(ADDON::ADDON_SCRIPT_MODULE, addons);
  for (unsigned int i = 0; i < addons.size(); ++i)
    path += PY_PATH_SEP + _P(addons[i]->LibPath());

  // and add on whatever our default path is
  path += PY_PATH_SEP;

  // we want to use sys.path so it includes site-packages
  // if this fails, default to using Py_GetPath
  PyObject *sysMod(PyImport_ImportModule((char*)"sys")); // must call Py_DECREF when finished
  PyObject *sysModDict(PyModule_GetDict(sysMod)); // borrowed ref, no need to delete
  PyObject *pathObj(PyDict_GetItemString(sysModDict, "path")); // borrowed ref, no need to delete

  if( pathObj && PyList_Check(pathObj) )
  {
    for( int i = 0; i < PyList_Size(pathObj); i++ )
    {
      PyObject *e = PyList_GetItem(pathObj, i); // borrowed ref, no need to delete
      if( e && PyString_Check(e) )
      {
          path += PyString_AsString(e); // returns internal data, don't delete or modify
          path += PY_PATH_SEP;
      }
    }
  }
  else
  {
    path += Py_GetPath();
  }
  Py_DECREF(sysMod); // release ref to sysMod

  // set current directory and python's path.
  if (m_argv != NULL)
    PySys_SetArgv(m_argc, m_argv);

  CLog::Log(LOGDEBUG, "%s - Setting the Python path to %s", __FUNCTION__, path.c_str());

  PySys_SetPath((char *)path.c_str());

  CLog::Log(LOGDEBUG, "%s - Entering source directory %s", __FUNCTION__, scriptDir.c_str());

  PyObject* module = PyImport_AddModule((char*)"__main__");
  PyObject* moduleDict = PyModule_GetDict(module);

  // when we are done initing we store thread state so we can be aborted
  PyThreadState_Swap(NULL);
  PyEval_ReleaseLock();

  // we need to check if we was asked to abort before we had inited
  bool stopping = false;
  { CSingleLock lock(m_pExecuter->m_critSection);
    m_threadState = state;
    stopping = m_stopping;
  }

  PyEval_AcquireLock();
  PyThreadState_Swap(state);

  if (!stopping)
  {
    if (m_type == 'F')
    {
      // run script from file
      // We need to have python open the file because on Windows the DLL that python
      //  is linked against may not be the DLL that xbmc is linked against so
      //  passing a FILE* to python from an fopen has the potential to crash.
      PyObject* file = PyFile_FromString((char *) _P(m_source).c_str(), (char*)"r");
      FILE *fp = PyFile_AsFile(file);

      if (fp)
      {
        PyObject *f = PyString_FromString(_P(m_source).c_str());
        PyDict_SetItemString(moduleDict, "__file__", f);
        if (addon.get() != NULL)
        {
          PyObject *pyaddonid = PyString_FromString(addon->ID().c_str());
          PyDict_SetItemString(moduleDict, "__xbmcaddonid__", pyaddonid);

          CStdString version = ADDON::GetXbmcApiVersionDependency(addon);
          PyObject *pyxbmcapiversion = PyString_FromString(version.c_str());
          PyDict_SetItemString(moduleDict, "__xbmcapiversion__", pyxbmcapiversion);

          CLog::Log(LOGDEBUG,"Instantiating addon using automatically obtained id of \"%s\" dependent on version %s of the xbmc.python api",addon->ID().c_str(),version.c_str());
        }
        Py_DECREF(f);
        PyRun_FileExFlags(fp, _P(m_source).c_str(), m_Py_file_input, moduleDict, moduleDict,1,NULL);
      }
      else
        CLog::Log(LOGERROR, "%s not found!", m_source);
    }
    else
    {
      //run script
      PyRun_String(m_source, m_Py_file_input, moduleDict, moduleDict);
    }
  }

  if (!PyErr_Occurred())
    CLog::Log(LOGINFO, "Scriptresult: Success");
  else if (PyErr_ExceptionMatches(PyExc_SystemExit))
    CLog::Log(LOGINFO, "Scriptresult: Aborted");
  else
  {
    PyObject* exc_type;
    PyObject* exc_value;
    PyObject* exc_traceback;
    PyObject* pystring;
    pystring = NULL;

    PyErr_Fetch(&exc_type, &exc_value, &exc_traceback);
    if (exc_type == 0 && exc_value == 0 && exc_traceback == 0)
    {
      CLog::Log(LOGINFO, "Strange: No Python exception occured");
    }
    else
    {
      if (exc_type != NULL && (pystring = PyObject_Str(exc_type)) != NULL && (PyString_Check(pystring)))
      {
          PyObject *tracebackModule;

          CLog::Log(LOGINFO, "-->Python script returned the following error<--");
          CLog::Log(LOGERROR, "Error Type: %s", PyString_AsString(PyObject_Str(exc_type)));
          if (PyObject_Str(exc_value))
            CLog::Log(LOGERROR, "Error Contents: %s", PyString_AsString(PyObject_Str(exc_value)));

          tracebackModule = PyImport_ImportModule((char*)"traceback");
          if (tracebackModule != NULL)
          {
            PyObject *tbList, *emptyString, *strRetval;

            tbList = PyObject_CallMethod(tracebackModule, (char*)"format_exception", (char*)"OOO", exc_type, exc_value == NULL ? Py_None : exc_value, exc_traceback == NULL ? Py_None : exc_traceback);
            emptyString = PyString_FromString("");
            strRetval = PyObject_CallMethod(emptyString, (char*)"join", (char*)"O", tbList);

            CLog::Log(LOGERROR, "%s", PyString_AsString(strRetval));

            Py_DECREF(tbList);
            Py_DECREF(emptyString);
            Py_DECREF(strRetval);
            Py_DECREF(tracebackModule);
          }
          CLog::Log(LOGINFO, "-->End of Python script error report<--");
      }
      else
      {
        pystring = NULL;
        CLog::Log(LOGINFO, "<unknown exception type>");
      }

      CGUIDialogKaiToast *pDlgToast = (CGUIDialogKaiToast*)g_windowManager.GetWindow(WINDOW_DIALOG_KAI_TOAST);
      if (pDlgToast)
      {
        CStdString desc;
        CStdString path;
        CStdString script;
        URIUtils::Split(m_source, path, script);
        if (script.Equals("default.py"))
        {
          CStdString path2;
          URIUtils::RemoveSlashAtEnd(path);
          URIUtils::Split(path, path2, script);
        }

        desc.Format(g_localizeStrings.Get(2100), script);
        pDlgToast->QueueNotification(CGUIDialogKaiToast::Error, g_localizeStrings.Get(257), desc);
      }
    }

    Py_XDECREF(exc_type);
    Py_XDECREF(exc_value); // caller owns all 3
    Py_XDECREF(exc_traceback); // already NULL'd out
    Py_XDECREF(pystring);
  }

  PyObject *m = PyImport_AddModule((char*)"xbmc");
  if(!m || PyObject_SetAttrString(m, (char*)"abortRequested", PyBool_FromLong(1)))
    CLog::Log(LOGERROR, "Scriptresult: failed to set abortRequested");

  // make sure all sub threads have finished
  for(PyThreadState* s = state->interp->tstate_head, *old = NULL; s;)
  {
    if(s == state)
    {
      s = s->next;
      continue;
    }
    if(old != s)
    {
      CLog::Log(LOGINFO, "Scriptresult: Waiting on thread %"PRIu64, (uint64_t)s->thread_id);
      old = s;
    }

    CPyThreadState pyState;
    Sleep(100);
    pyState.Restore();

    s = state->interp->tstate_head;
  }

  // pending calls must be cleared out
  PyXBMC_ClearPendingCalls(state);

  PyThreadState_Swap(NULL);
  PyEval_ReleaseLock();

  { CSingleLock lock(m_pExecuter->m_critSection);
    m_threadState = NULL;
  }

  PyEval_AcquireLock();
  PyThreadState_Swap(state);

  m_pExecuter->DeInitializeInterpreter();

  Py_EndInterpreter(state);
  PyThreadState_Swap(NULL);

  PyEval_ReleaseLock();
}
コード例 #8
0
ファイル: XBPyThread.cpp プロジェクト: Jdad/xbmc
void XBPyThread::Process()
{
  CLog::Log(LOGDEBUG,"Python thread: start processing");

  int m_Py_file_input = Py_file_input;

  // get the global lock
  PyEval_AcquireLock();
  PyThreadState* state = Py_NewInterpreter();
  if (!state)
  {
    PyEval_ReleaseLock();
    CLog::Log(LOGERROR,"Python thread: FAILED to get thread state!");
    return;
  }
  // swap in my thread state
  PyThreadState_Swap(state);

  XBMCAddon::AddonClass::Ref<XBMCAddon::Python::LanguageHook> languageHook(new XBMCAddon::Python::LanguageHook(state->interp));
  languageHook->RegisterMe();

  m_pExecuter->InitializeInterpreter(addon);

  CLog::Log(LOGDEBUG, "%s - The source file to load is %s", __FUNCTION__, m_source);

  // get path from script file name and add python path's
  // this is used for python so it will search modules from script path first
  CStdString scriptDir;
  URIUtils::GetDirectory(CSpecialProtocol::TranslatePath(m_source), scriptDir);
  URIUtils::RemoveSlashAtEnd(scriptDir);
  CStdString path = scriptDir;

  // add on any addon modules the user has installed
  ADDON::VECADDONS addons;
  ADDON::CAddonMgr::Get().GetAddons(ADDON::ADDON_SCRIPT_MODULE, addons);
  for (unsigned int i = 0; i < addons.size(); ++i)
#ifdef TARGET_WINDOWS
  {
    CStdString strTmp(CSpecialProtocol::TranslatePath(addons[i]->LibPath()));
    g_charsetConverter.utf8ToSystem(strTmp);
    path += PY_PATH_SEP + strTmp;
  }
#else
    path += PY_PATH_SEP + CSpecialProtocol::TranslatePath(addons[i]->LibPath());
#endif

  // and add on whatever our default path is
  path += PY_PATH_SEP;

  // we want to use sys.path so it includes site-packages
  // if this fails, default to using Py_GetPath
  PyObject *sysMod(PyImport_ImportModule((char*)"sys")); // must call Py_DECREF when finished
  PyObject *sysModDict(PyModule_GetDict(sysMod)); // borrowed ref, no need to delete
  PyObject *pathObj(PyDict_GetItemString(sysModDict, "path")); // borrowed ref, no need to delete

  if( pathObj && PyList_Check(pathObj) )
  {
    for( int i = 0; i < PyList_Size(pathObj); i++ )
    {
      PyObject *e = PyList_GetItem(pathObj, i); // borrowed ref, no need to delete
      if( e && PyString_Check(e) )
      {
        path += PyString_AsString(e); // returns internal data, don't delete or modify
        path += PY_PATH_SEP;
      }
    }
  }
  else
  {
    path += Py_GetPath();
  }
  Py_DECREF(sysMod); // release ref to sysMod

  // set current directory and python's path.
  if (m_argv != NULL)
    PySys_SetArgv(m_argc, m_argv);

  CLog::Log(LOGDEBUG, "%s - Setting the Python path to %s", __FUNCTION__, path.c_str());

  PySys_SetPath((char *)path.c_str());

  CLog::Log(LOGDEBUG, "%s - Entering source directory %s", __FUNCTION__, scriptDir.c_str());

  PyObject* module = PyImport_AddModule((char*)"__main__");
  PyObject* moduleDict = PyModule_GetDict(module);

  // when we are done initing we store thread state so we can be aborted
  PyThreadState_Swap(NULL);
  PyEval_ReleaseLock();

  // we need to check if we was asked to abort before we had inited
  bool stopping = false;
  { CSingleLock lock(m_critSec);
    m_threadState = state;
    stopping = m_stopping;
  }

  PyEval_AcquireLock();
  PyThreadState_Swap(state);

  if (!stopping)
  {
    try
    {
    if (m_type == 'F')
    {
      // run script from file
      // We need to have python open the file because on Windows the DLL that python
      //  is linked against may not be the DLL that xbmc is linked against so
      //  passing a FILE* to python from an fopen has the potential to crash.
      PyObject* file = PyFile_FromString((char *) CSpecialProtocol::TranslatePath(m_source).c_str(), (char*)"r");
      FILE *fp = PyFile_AsFile(file);

      if (fp)
      {
        PyObject *f = PyString_FromString(CSpecialProtocol::TranslatePath(m_source).c_str());
        PyDict_SetItemString(moduleDict, "__file__", f);
        if (addon.get() != NULL)
        {
          PyObject *pyaddonid = PyString_FromString(addon->ID().c_str());
          PyDict_SetItemString(moduleDict, "__xbmcaddonid__", pyaddonid);

          CStdString version = ADDON::GetXbmcApiVersionDependency(addon);
          PyObject *pyxbmcapiversion = PyString_FromString(version.c_str());
          PyDict_SetItemString(moduleDict, "__xbmcapiversion__", pyxbmcapiversion);

          CLog::Log(LOGDEBUG,"Instantiating addon using automatically obtained id of \"%s\" dependent on version %s of the xbmc.python api",addon->ID().c_str(),version.c_str());
        }
        Py_DECREF(f);
        XBMCAddon::Python::PyContext pycontext; // this is a guard class that marks this callstack as being in a python context
        PyRun_FileExFlags(fp, CSpecialProtocol::TranslatePath(m_source).c_str(), m_Py_file_input, moduleDict, moduleDict,1,NULL);
      }
      else
        CLog::Log(LOGERROR, "%s not found!", m_source);
    }
    else
    {
      //run script
      PyRun_String(m_source, m_Py_file_input, moduleDict, moduleDict);
    }
    }
    catch (const XbmcCommons::Exception& e)
    {
      e.LogThrowMessage();
    }
    catch (...)
    {
      CLog::Log(LOGERROR, "failure in %s", m_source);
    }
  }

  bool systemExitThrown = false;
  if (!PyErr_Occurred())
    CLog::Log(LOGINFO, "Scriptresult: Success");
  else if (PyErr_ExceptionMatches(PyExc_SystemExit))
  {
    systemExitThrown = true;
    CLog::Log(LOGINFO, "Scriptresult: Aborted");
  }
  else
  {
    PythonBindings::PythonToCppException e;
    e.LogThrowMessage();

    {
      CPyThreadState releaseGil;
      CSingleLock gc(g_graphicsContext);

      CGUIDialogKaiToast *pDlgToast = (CGUIDialogKaiToast*)g_windowManager.GetWindow(WINDOW_DIALOG_KAI_TOAST);
      if (pDlgToast)
      {
        CStdString desc;
        CStdString path;
        CStdString script;
        URIUtils::Split(m_source, path, script);
        if (script.Equals("default.py"))
        {
          CStdString path2;
          URIUtils::RemoveSlashAtEnd(path);
          URIUtils::Split(path, path2, script);
        }

        desc.Format(g_localizeStrings.Get(2100), script);
        pDlgToast->QueueNotification(CGUIDialogKaiToast::Error, g_localizeStrings.Get(257), desc);
      }
    }
  }

  PyObject *m = PyImport_AddModule((char*)"xbmc");
  if(!m || PyObject_SetAttrString(m, (char*)"abortRequested", PyBool_FromLong(1)))
    CLog::Log(LOGERROR, "Scriptresult: failed to set abortRequested");

  // make sure all sub threads have finished
  for(PyThreadState* s = state->interp->tstate_head, *old = NULL; s;)
  {
    if(s == state)
    {
      s = s->next;
      continue;
    }
    if(old != s)
    {
      CLog::Log(LOGINFO, "Scriptresult: Waiting on thread %"PRIu64, (uint64_t)s->thread_id);
      old = s;
    }

    CPyThreadState pyState;
    Sleep(100);
    pyState.Restore();

    s = state->interp->tstate_head;
  }

  // pending calls must be cleared out
  XBMCAddon::RetardedAsynchCallbackHandler::clearPendingCalls(state);

  PyThreadState_Swap(NULL);
  PyEval_ReleaseLock();

  //set stopped event - this allows ::stop to run and kill remaining threads
  //this event has to be fired without holding m_critSec
  //
  //Also the GIL (PyEval_AcquireLock) must not be held
  //if not obeyed there is still no deadlock because ::stop waits with timeout (smart one!)
  stoppedEvent.Set();

  { CSingleLock lock(m_critSec);
    m_threadState = NULL;
  }

  PyEval_AcquireLock();
  PyThreadState_Swap(state);

  m_pExecuter->DeInitializeInterpreter();

  // run the gc before finishing
  //
  // if the script exited by throwing a SystemExit excepton then going back
  // into the interpreter causes this python bug to get hit:
  //    http://bugs.python.org/issue10582
  // and that causes major failures. So we are not going to go back in
  // to run the GC if that's the case.
  if (!m_stopping && languageHook->HasRegisteredAddonClasses() && !systemExitThrown &&
      PyRun_SimpleString(GC_SCRIPT) == -1)
    CLog::Log(LOGERROR,"Failed to run the gc to clean up after running prior to shutting down the Interpreter %s",m_source);

  Py_EndInterpreter(state);

  // If we still have objects left around, produce an error message detailing what's been left behind
  if (languageHook->HasRegisteredAddonClasses())
    CLog::Log(LOGWARNING, "The python script \"%s\" has left several "
              "classes in memory that we couldn't clean up. The classes include: %s",
              m_source, getListOfAddonClassesAsString(languageHook).c_str());

  // unregister the language hook
  languageHook->UnregisterMe();

  PyEval_ReleaseLock();

}
コード例 #9
0
ファイル: sanlock.c プロジェクト: edwardbadboy/sanlock-ubuntu
static int
__parse_resource(PyObject *obj, struct sanlk_resource **res_ret)
{
    int i, num_disks, res_len;
    struct sanlk_resource *res;

    num_disks = PyList_Size(obj);

    res_len = sizeof(struct sanlk_resource) +
                        (sizeof(struct sanlk_disk) * num_disks);
    res = malloc(res_len);

    if (res == NULL) {
        PyErr_NoMemory();
        return -1;
    }

    memset(res, 0, res_len);
    res->num_disks = num_disks;

    for (i = 0; i < num_disks; i++) {
        char *p = NULL;
        PyObject *tuple, *path = NULL, *offset = NULL;

        tuple = PyList_GetItem(obj, i);

        if (PyTuple_Check(tuple)) {
            if (PyTuple_Size(tuple) != 2) {
                __set_exception(EINVAL, "Invalid resource tuple");
                goto exit_fail;
            }

            path = PyTuple_GetItem(tuple, 0);
            offset = PyTuple_GetItem(tuple, 1);

            p = PyString_AsString(path);

            if (!PyInt_Check(offset)) {
                __set_exception(EINVAL, "Invalid resource offset");
                goto exit_fail;
            }
        } else if (PyString_Check(tuple)) {
            p = PyString_AsString(tuple);
        }

        if (p == NULL) {
            __set_exception(EINVAL, "Invalid resource path");
            goto exit_fail;
        }

        strncpy(res->disks[i].path, p, SANLK_PATH_LEN - 1);

        if (offset == NULL) {
            res->disks[i].offset = 0;
        } else {
            res->disks[i].offset = PyInt_AsLong(offset);
        }
    }

    *res_ret = res;
    return 0;

exit_fail:
    free(res);
    return -1;
}
コード例 #10
0
ファイル: script.c プロジェクト: dhirajkhatiwada1/uludag
//! Executes given method of app/model
int
py_execute(const char *app, const char *model, const char *method, PyObject *py_args, PyObject **py_ret)
{
    /*!
     * Loads app/model.py and calls method with given arguments. If app or module is null, this
     * function will execute specified method on CORE module.
     *
     * @app Application
     * @model Model
     * @method Method
     * @py_args Arguments
     * @py_ret Pointer to returned value
     * @return 0 on success, -1 on missing file, -2 on Python error, -3 on access denied, -4 on PolicyKit error
     *
     */

    PyObject *py_mod_script, *py_mod_builtin;
    PyObject *py_dict_script, *py_dict_builtin;
    PyObject *py_code, *py_method_code, *py_kwargs, *py_func = NULL;
    PyMethodDef *py_method;

    PyObject *py_module, *py_dict, *py_list;
    PyObject *py_dict_core;
    PyObject *py_mod_core;

    // Add core module directory to sys.path
    py_module = PyImport_ImportModule("sys");
    py_dict = PyModule_GetDict(py_module);
    py_list = PyDict_GetItemString(py_dict, "path");
    PyList_Insert(py_list, 0, PyString_FromString(config_dir_modules));

    // Put CSL methods into __builtin__
    py_mod_builtin = PyImport_AddModule("__builtin__");
    py_dict_builtin = PyModule_GetDict(py_mod_builtin);
    for (py_method = methods; py_method->ml_name; py_method++) {
        py_method_code = PyCFunction_New(py_method, NULL);
        PyDict_SetItemString(py_dict_builtin, py_method->ml_name, py_method_code);
    }

    // If model and application name given, try to execute method on registered script
    if (model != NULL && app != NULL) {
        // Import script
        int size = strlen(config_dir_scripts) + 1 + strlen(model) + 1 + strlen(app) + 3 + 1;
        char *fn_script = malloc(size);
        if (fn_script == NULL) oom();
        snprintf(fn_script, size, "%s/%s/%s.py", config_dir_scripts, model, app);
        fn_script[size - 1] = 0;

        // Check script existance
        if (access(fn_script, R_OK) != 0) {
            log_error("Unable to find script: %s\n", fn_script);
            PyErr_Format(PyExc_COMAR_Internal, "Unable to find '%s'", fn_script);
            free(fn_script);
            return -1;
        }

        // Load script file
        char *code = load_file(fn_script, NULL);
        if (!code) {
            log_error("Unable to read script: %s\n", fn_script);
            PyErr_Format(PyExc_COMAR_Internal, "Unable to read '%s'", fn_script);
            free(fn_script);
            return -1;
        }

        // Compile script
        py_code = Py_CompileString(code, fn_script, Py_file_input);
        free(code);
        if (!py_code) {
            log_error("Unable to compile script: %s\n", fn_script);
            free(fn_script);
            return -2;
        }

        // Import script as "csl" module
        py_mod_script = PyImport_ExecCodeModule("csl", py_code);
        if (!py_mod_script) {
            log_error("Unable to exec code module script: %s\n", fn_script);
            free(fn_script);
            return -2;
        }

        free(fn_script);

        // Look for 'method()' in script
        py_dict_script = PyModule_GetDict(py_mod_script);
        py_func = PyDict_GetItemString(py_dict_script, method);
    }
    // Else, execute method on core module
    else {
        // Import core module
        py_mod_core = PyImport_ImportModule("core");
        if (!py_mod_core) {
            log_error("Unable to import core module.\n");
            return -2;
        }

        // Look for 'method()' in script
        py_dict_core = PyModule_GetDict(py_mod_core);
        py_func = PyDict_GetItemString(py_dict_core, method);
    }

    // Finally, run method
    if (!py_func) {
        if (config_ignore_missing) {
            Py_INCREF(Py_None);
            *py_ret = Py_None;
        }
        else {
            PyErr_Format(PyExc_COMAR_Missing, "Method '%s' is not defined in script", method);
            return -2;
        }
    }
    else if (!PyCallable_Check(py_func)) {
        PyErr_Format(PyExc_COMAR_Script, "Method '%s' is not callable in script", method);
        return -2;
    }
    else {
        // Check if PolicyKit action defined at runtime
        if (PyObject_HasAttrString(py_func, "policy_action_id")) {
            const char *action_id = PyString_AsString(PyObject_GetAttrString(py_func, "policy_action_id"));
            const char *sender = dbus_message_get_sender(my_proc.bus_msg);

            PolKitResult result;
            if (policy_check(sender, action_id, &result) == 0) {
                if (result != POLKIT_RESULT_YES) {
                    PyErr_Format(PyExc_PolicyKit, action_id);
                    return -3;
                }
            }
            else {
                PyErr_Format(PyExc_PolicyKit, "error");
                return -4;
            }
        }

        py_kwargs = PyDict_New();
        *py_ret = PyObject_Call(py_func, py_args, py_kwargs);
        if (!*py_ret) {
            return -2;
        }
    }

    return 0;
}
コード例 #11
0
ファイル: post.c プロジェクト: clones/kaa
PyObject *
Xine_Post_PyObject_set_parameters(Xine_Post_PyObject *self, PyObject *args, PyObject *kwargs)
{
    xine_post_in_t *input_api;
    xine_post_api_t *api;
    xine_post_api_descr_t *desc;
    xine_post_api_parameter_t *parm;
    char *data;
    PyObject *dict;

    if (!PyArg_ParseTuple(args, "O!", &PyDict_Type, &dict))
        return NULL;

    input_api = (xine_post_in_t *)xine_post_input(self->post, "parameters");
    if (!input_api) {
        Py_INCREF(Py_None);
        return Py_None;
    }

    api = (xine_post_api_t *)input_api->data;
    desc = api->get_param_descr();
    parm = desc->parameter;
    data = (void *)malloc(desc->struct_size);
    api->get_parameters(self->post, (void *)data);

    while (parm->type != POST_PARAM_TYPE_LAST) {
        PyObject *value = PyDict_GetItemString(dict, parm->name);
        if (!value) {
            parm++;
            continue;
        }

        switch(parm->type) {
            case POST_PARAM_TYPE_INT:
                *(int *)(data + parm->offset) =  PyLong_AsLong(value);
                break;
            case POST_PARAM_TYPE_DOUBLE:
                *(double *)(data + parm->offset) =  PyFloat_AsDouble(value);
                break;
            case POST_PARAM_TYPE_CHAR:
                strncpy((char *)(data + parm->offset), PyString_AsString(value), parm->size);
                break;
            case POST_PARAM_TYPE_STRING:
            {
                char *tmp;
                tmp = (void *)calloc(1, PySequence_Size(value) + 1);
                strcpy(tmp, PyString_AsString(value));
                *(char **)(data + parm->offset) =  tmp;
                break;
            }
            case POST_PARAM_TYPE_STRINGLIST:
            {
                int i;
                char **strings, *tmp;
                strings = (char **)malloc(PyList_Size(value) + 1);
                for (i = 0; i < PyList_Size(value); i++) {
                    PyObject *o = PyList_GetItem(value, i);
                    tmp = (void *)calloc(1, PySequence_Size(o) + 1);
                    strcpy(tmp, PyString_AsString(o));
                    strings[i] = tmp;
                    Py_DECREF(o);
                }
                strings[i] = NULL;
                *(char **)(data + parm->offset) = (char *)strings;
                break;
            }
            case POST_PARAM_TYPE_BOOL:
                *(int *)(data + parm->offset) =  PyLong_AsLong(value);
                break;
        }
        parm++;
    }

    Py_BEGIN_ALLOW_THREADS
    api->set_parameters(self->post, (void *)data);
    Py_END_ALLOW_THREADS
    free(data);
    if (PyErr_Occurred())
        return NULL;

    Py_INCREF(Py_None);
    return Py_None;
}
コード例 #12
0
ファイル: pyewf_file_entry.c プロジェクト: zhangway100/libewf
/* Reads a buffer of file entry data at a specific offset from EWF file(s)
 * Returns a Python object holding the data if successful or NULL on error
 */
PyObject *pyewf_file_entry_read_buffer_at_offset(
           pyewf_file_entry_t *pyewf_file_entry,
           PyObject *arguments,
           PyObject *keywords )
{
	libcerror_error_t *error    = NULL;
	PyObject *string_object     = NULL;
	static char *function       = "pyewf_file_entry_read_buffer_at_offset";
	static char *keyword_list[] = { "size", "offset", NULL };
	char *buffer                = NULL;
	off64_t read_offset         = 0;
	ssize_t read_count          = 0;
	int read_size               = 0;

	if( pyewf_file_entry == NULL )
	{
		PyErr_Format(
		 PyExc_TypeError,
		 "%s: invalid pyewf file_entry.",
		 function );

		return( NULL );
	}
	if( pyewf_file_entry->file_entry == NULL )
	{
		PyErr_Format(
		 PyExc_TypeError,
		 "%s: invalid pyewf file_entry - missing libewf file_entry.",
		 function );

		return( NULL );
	}
	if( PyArg_ParseTupleAndKeywords(
	     arguments,
	     keywords,
	     "i|L",
	     keyword_list,
	     &read_size,
	     &read_offset ) == 0 )
	{
		return( NULL );
	}
	if( read_size < 0 )
	{
		PyErr_Format(
		 PyExc_ValueError,
		 "%s: invalid argument read size value less than zero.",
		 function );

		return( NULL );
	}
	/* Make sure the data fits into a memory buffer
	 */
	if( read_size > INT_MAX )
	{
		PyErr_Format(
		 PyExc_ValueError,
		 "%s: invalid argument read size value exceeds maximum.",
		 function );

		return( NULL );
	}
	if( read_offset < 0 )
	{
		PyErr_Format(
		 PyExc_ValueError,
		 "%s: invalid argument read offset value less than zero.",
		 function );

		return( NULL );
	}
	/* Make sure the data fits into a memory buffer
	 */
#if PY_MAJOR_VERSION >= 3
	string_object = PyBytes_FromStringAndSize(
	                 NULL,
	                 read_size );

	buffer = PyBytes_AsString(
	          string_object );
#else
	string_object = PyString_FromStringAndSize(
	                 NULL,
	                 read_size );

	buffer = PyString_AsString(
	          string_object );
#endif
	Py_BEGIN_ALLOW_THREADS

	read_count = libewf_file_entry_read_buffer_at_offset(
	              pyewf_file_entry->file_entry,
	              (uint8_t *) buffer,
	              (size_t) read_size,
	              (off64_t) read_offset,
	              &error );

	Py_END_ALLOW_THREADS

	if( read_count <= -1 )
	{
		pyewf_error_raise(
		 error,
		 PyExc_IOError,
		 "%s: unable to read data.",
		 function );

		libcerror_error_free(
		 &error );

		Py_DecRef(
		 (PyObject *) string_object );

		return( NULL );
	}
	/* Need to resize the string here in case read_size was not fully read.
	 */
#if PY_MAJOR_VERSION >= 3
	if( _PyBytes_Resize(
	     &string_object,
	     (Py_ssize_t) read_count ) != 0 )
#else
	if( _PyString_Resize(
	     &string_object,
	     (Py_ssize_t) read_count ) != 0 )
#endif
	{
		Py_DecRef(
		 (PyObject *) string_object );

		return( NULL );
	}
	return( string_object );
}
コード例 #13
0
ファイル: vcodec.c プロジェクト: audioburn/pymedia-redux-full
// ---------------------------------------------------------------------------------
static PyObject * Frame_Convert( PyVFrameObject* obj, PyObject *args)
{
	PyVFrameObject *cSrc= obj;
	int iFormat, iWidth, iHeight, iDepth= 1, iPlanes= 3, i;
	PyObject *acPlanes[ 3 ]= { NULL, NULL, NULL };
	PyVFrameObject* cRes;

	// Create new AVPicture in a new format
	AVPicture cSrcPict;
	AVPicture cDstPict;

	if (!PyArg_ParseTuple(args, "i|(ii)", &iFormat, &iWidth, &iHeight ))
		return NULL;

	// Make sure the frame data is not copied
	PyVFrame2AVFrame( obj, (AVFrame*)&cSrcPict, 0 );
	memset( &cDstPict.data[ 0 ], 0, sizeof( cDstPict.data ) );

	// Create new VFrame
	cRes= (PyVFrameObject*)PyObject_New( PyVFrameObject, &VFrameType );
	if( !cRes )
		return NULL;
	// Start assembling result into frame
	memset( &cRes->cData[ 0 ], 0, sizeof( cRes->cData ) );

	// Find format by its id
	switch( iFormat )
	{
		case PIX_FMT_YUV420P:
		case PIX_FMT_YUV422:
		case PIX_FMT_YUV422P:
		case PIX_FMT_YUV444P:
		case PIX_FMT_YUV410P:
		case PIX_FMT_YUV411P:
		case PIX_FMT_YUVJ420P:
		case PIX_FMT_YUVJ422P:
		case PIX_FMT_YUVJ444P:
			// 3 planes
			acPlanes[ 1 ]= PyString_FromStringAndSize( NULL, cSrc->width* cSrc->height/ 4 );
			acPlanes[ 2 ]= PyString_FromStringAndSize( NULL, cSrc->width* cSrc->height/ 4 );
			cDstPict.data[ 1 ]= PyString_AsString( acPlanes[ 1 ] );
			cDstPict.data[ 2 ]= PyString_AsString( acPlanes[ 2 ] );
			cDstPict.linesize[ 1 ]= cDstPict.linesize[ 2 ]= cSrc->width/ 2;
			break;
		case PIX_FMT_RGBA32:
			iDepth++;
		case PIX_FMT_RGB24:
		case PIX_FMT_BGR24:
			iDepth++;
		case PIX_FMT_RGB565:
		case PIX_FMT_RGB555:
			iDepth++;
		case PIX_FMT_GRAY8:
		case PIX_FMT_MONOWHITE:
		case PIX_FMT_MONOBLACK:
		case PIX_FMT_PAL8:
			//iDepth++;
			iPlanes= 1;
			break;
		default:
			// Raise an error if the format is not supported
			PyErr_Format( g_cErr, "Video frame with format %d cannot be created", iFormat );
			return NULL;
	}
	// 1 plane
	acPlanes[ 0 ]= PyString_FromStringAndSize( NULL, cSrc->width* cSrc->height* iDepth );
	cDstPict.linesize[ 0 ]= cSrc->width* iDepth;
	cDstPict.data[ 0 ]= PyString_AsString( acPlanes[ 0 ] );

	// Convert images
	if( img_convert( &cDstPict, iFormat, &cSrcPict, cSrc->pix_fmt, cSrc->width, cSrc->height )== -1 )
	{
		PyErr_Format( g_cErr, "Video frame with format %d cannot be converted to %d", cSrc->pix_fmt, iFormat );
		if( acPlanes[ 0 ] )
		{
			Py_DECREF( acPlanes[ 0 ] );
		}
		if( acPlanes[ 1 ] )
		{
			Py_DECREF( acPlanes[ 1 ] );
		}
		if( acPlanes[ 2 ] )
		{
			Py_DECREF( acPlanes[ 2 ] );
		}
		return NULL;
	}

	//Preprocess_Frame(obj, picture,&buffer_to_free);
	cRes->aspect_ratio= cSrc->aspect_ratio;
	cRes->frame_rate= cSrc->frame_rate;
	cRes->frame_rate_base= cSrc->frame_rate_base;
	cRes->height= cSrc->height;
	cRes->width= cSrc->width;
	cRes->pix_fmt= iFormat;
	cRes->pict_type= cSrc->pict_type;
        cRes->pts= -1;
	// Copy string(s)
	for( i= 0; i< iPlanes; i++ )
		cRes->cData[ i ]= (PyVCStringObject*)acPlanes[ i ];

	return (PyObject*)cRes;
}
コード例 #14
0
ファイル: getargs.c プロジェクト: Claruarius/stblinux-2.6.37
static char *
convertsimple1(PyObject *arg, char **p_format, va_list *p_va)
{
	char *format = *p_format;
	char c = *format++;
	
	switch (c) {
	
	case 'b': /* unsigned byte -- very short int */
		{
			char *p = va_arg(*p_va, char *);
			long ival = PyInt_AsLong(arg);
			if (ival == -1 && PyErr_Occurred())
				return "integer<b>";
			else if (ival < 0) {
				PyErr_SetString(PyExc_OverflowError,
			      "unsigned byte integer is less than minimum");
				return "integer<b>";
			}
			else if (ival > UCHAR_MAX) {
				PyErr_SetString(PyExc_OverflowError,
			      "unsigned byte integer is greater than maximum");
				return "integer<b>";
			}
			else
				*p = (unsigned char) ival;
			break;
		}
	
	case 'B': /* byte sized bitfield - both signed and unsigned values allowed */
		{
			char *p = va_arg(*p_va, char *);
			long ival = PyInt_AsLong(arg);
			if (ival == -1 && PyErr_Occurred())
				return "integer<b>";
			else if (ival < SCHAR_MIN) {
				PyErr_SetString(PyExc_OverflowError,
			      "byte-sized integer bitfield is less than minimum");
				return "integer<B>";
			}
			else if (ival > (int)UCHAR_MAX) {
				PyErr_SetString(PyExc_OverflowError,
			      "byte-sized integer bitfield is greater than maximum");
				return "integer<B>";
			}
			else
				*p = (unsigned char) ival;
			break;
		}
	
	case 'h': /* signed short int */
		{
			short *p = va_arg(*p_va, short *);
			long ival = PyInt_AsLong(arg);
			if (ival == -1 && PyErr_Occurred())
				return "integer<h>";
			else if (ival < SHRT_MIN) {
				PyErr_SetString(PyExc_OverflowError,
			      "signed short integer is less than minimum");
				return "integer<h>";
			}
			else if (ival > SHRT_MAX) {
				PyErr_SetString(PyExc_OverflowError,
			      "signed short integer is greater than maximum");
				return "integer<h>";
			}
			else
				*p = (short) ival;
			break;
		}
	
	case 'H': /* short int sized bitfield, both signed and unsigned allowed */
		{
			unsigned short *p = va_arg(*p_va, unsigned short *);
			long ival = PyInt_AsLong(arg);
			if (ival == -1 && PyErr_Occurred())
				return "integer<H>";
			else if (ival < SHRT_MIN) {
				PyErr_SetString(PyExc_OverflowError,
			      "short integer bitfield is less than minimum");
				return "integer<H>";
			}
			else if (ival > USHRT_MAX) {
				PyErr_SetString(PyExc_OverflowError,
			      "short integer bitfield is greater than maximum");
				return "integer<H>";
			}
			else
				*p = (unsigned short) ival;
			break;
		}
	
	case 'i': /* signed int */
		{
			int *p = va_arg(*p_va, int *);
			long ival = PyInt_AsLong(arg);
			if (ival == -1 && PyErr_Occurred())
				return "integer<i>";
			else if (ival > INT_MAX) {
				PyErr_SetString(PyExc_OverflowError,
				    "signed integer is greater than maximum");
				return "integer<i>";
			}
			else if (ival < INT_MIN) {
				PyErr_SetString(PyExc_OverflowError,
				    "signed integer is less than minimum");
				return "integer<i>";
			}
			else
				*p = ival;
			break;
		}
	case 'l': /* long int */
		{
			long *p = va_arg(*p_va, long *);
			long ival = PyInt_AsLong(arg);
			if (ival == -1 && PyErr_Occurred())
				return "integer<l>";
			else
				*p = ival;
			break;
		}
	
#ifdef HAVE_LONG_LONG
	case 'L': /* LONG_LONG */
		{
			LONG_LONG *p = va_arg( *p_va, LONG_LONG * );
			LONG_LONG ival = PyLong_AsLongLong( arg );
			if( ival == (LONG_LONG)-1 && PyErr_Occurred() ) {
				return "long<L>";
			} else {
				*p = ival;
			}
			break;
		}
#endif
	
	case 'f': /* float */
		{
			float *p = va_arg(*p_va, float *);
			double dval = PyFloat_AsDouble(arg);
			if (PyErr_Occurred())
				return "float<f>";
			else
				*p = (float) dval;
			break;
		}
	
	case 'd': /* double */
		{
			double *p = va_arg(*p_va, double *);
			double dval = PyFloat_AsDouble(arg);
			if (PyErr_Occurred())
				return "float<d>";
			else
				*p = dval;
			break;
		}
	
#ifndef WITHOUT_COMPLEX
	case 'D': /* complex double */
		{
			Py_complex *p = va_arg(*p_va, Py_complex *);
			Py_complex cval;
			cval = PyComplex_AsCComplex(arg);
			if (PyErr_Occurred())
				return "complex<D>";
			else
				*p = cval;
			break;
		}
#endif /* WITHOUT_COMPLEX */
	
	case 'c': /* char */
		{
			char *p = va_arg(*p_va, char *);
			if (PyString_Check(arg) && PyString_Size(arg) == 1)
				*p = PyString_AsString(arg)[0];
			else
				return "char";
			break;
		}
	
	case 's': /* string */
		{
			if (*format == '#') {
				void **p = (void **)va_arg(*p_va, char **);
				int *q = va_arg(*p_va, int *);

				if (PyString_Check(arg)) {
				    *p = PyString_AS_STRING(arg);
				    *q = PyString_GET_SIZE(arg);
				}
				else if (PyUnicode_Check(arg)) {
				    arg = _PyUnicode_AsDefaultEncodedString(
							            arg, NULL);
				    if (arg == NULL)
					return "unicode conversion error";
				    *p = PyString_AS_STRING(arg);
				    *q = PyString_GET_SIZE(arg);
				}
				else { /* any buffer-like object */
				    PyBufferProcs *pb = arg->ob_type->tp_as_buffer;
				    int count;
				    if ( pb == NULL ||
					 pb->bf_getreadbuffer == NULL ||
					 pb->bf_getsegcount == NULL )
					return "read-only buffer";
				    if ( (*pb->bf_getsegcount)(arg, NULL) != 1 )
					return "single-segment read-only buffer";
				    if ( (count =
					  (*pb->bf_getreadbuffer)(arg, 0, p)) < 0 )
					return "(unspecified)";
				    *q = count;
				}
				format++;
			} else {
				char **p = va_arg(*p_va, char **);
			
				if (PyString_Check(arg))
				    *p = PyString_AS_STRING(arg);
				else if (PyUnicode_Check(arg)) {
				    arg = _PyUnicode_AsDefaultEncodedString(
							            arg, NULL);
				    if (arg == NULL)
					return "unicode conversion error";
				    *p = PyString_AS_STRING(arg);
				}
				else
				  return "string";
				if ((int)strlen(*p) != PyString_Size(arg))
				  return "string without null bytes";
			}
			break;
		}
コード例 #15
0
PyObject *myx_py_grt_ls(PyObject *self, PyObject *args)
{
  char *path= NULL;
  MYX_GRT_VALUE *curnode;
  PyObject *content;
  MYX_GRT *grt= myx_py_get_grt()->grt;
  unsigned int i;

  if (!PyArg_ParseTuple(args, "|z", &path))
    return NULL;
  
  if (!path)
  {
    curnode= myx_grt_dict_item_get_by_path(grt, 
                                           grt->root,
                                           grt->shell->data->cwd);
  }
  else
  {
    path= myx_grt_get_abspath(grt->shell->data->cwd, path);
    if (!path)
    {
      PyErr_SetString(PyExc_ValueError, "invalid path");
      return NULL;
    }
    curnode= myx_grt_dict_item_get_by_path(grt,
                                           grt->root,
                                           path);
  }

  if (curnode)
  {
    switch (myx_grt_value_get_type(curnode))
    {
    case MYX_LIST_VALUE:
      for (i= 0; i < curnode->value.l->items_num; i++)
        print_value(grt, curnode->value.l->items[i]);
      break;

    case MYX_DICT_VALUE:
      for (i= 0; i < curnode->value.d->items_num; i++)
      {
        myx_grt_printf(grt, "%s => ", curnode->value.d->items[i].key);
        print_value(grt, curnode->value.d->items[i].value);
      }
      break;

    default:
      content= PyObject_Str((PyObject*)curnode);
      if (content)
      {
        myx_grt_printf(grt, PyString_AsString(content));
        Py_DECREF(content);
      }
      break;
    }
  }
  else
  {
    PyErr_Format(PyExc_KeyError, "invalid tree path '%s'", 
                 path ? path : grt->shell->data->cwd);
  }
  g_free(path);
  Py_INCREF(Py_None);
  return Py_None;
}
コード例 #16
0
ファイル: row.c プロジェクト: 1310701102/sl4a
PyObject* pysqlite_row_subscript(pysqlite_Row* self, PyObject* idx)
{
    long _idx;
    char* key;
    int nitems, i;
    char* compare_key;

    char* p1;
    char* p2;

    PyObject* item;

    if (PyInt_Check(idx)) {
        _idx = PyInt_AsLong(idx);
        item = PyTuple_GetItem(self->data, _idx);
        Py_XINCREF(item);
        return item;
    } else if (PyLong_Check(idx)) {
        _idx = PyLong_AsLong(idx);
        item = PyTuple_GetItem(self->data, _idx);
        Py_XINCREF(item);
        return item;
    } else if (PyString_Check(idx)) {
        key = PyString_AsString(idx);

        nitems = PyTuple_Size(self->description);

        for (i = 0; i < nitems; i++) {
            compare_key = PyString_AsString(PyTuple_GET_ITEM(PyTuple_GET_ITEM(self->description, i), 0));
            if (!compare_key) {
                return NULL;
            }

            p1 = key;
            p2 = compare_key;

            while (1) {
                if ((*p1 == (char)0) || (*p2 == (char)0)) {
                    break;
                }

                if ((*p1 | 0x20) != (*p2 | 0x20)) {
                    break;
                }

                p1++;
                p2++;
            }

            if ((*p1 == (char)0) && (*p2 == (char)0)) {
                /* found item */
                item = PyTuple_GetItem(self->data, i);
                Py_INCREF(item);
                return item;
            }

        }

        PyErr_SetString(PyExc_IndexError, "No item with that key");
        return NULL;
    } else if (PySlice_Check(idx)) {
        PyErr_SetString(PyExc_ValueError, "slices not implemented, yet");
        return NULL;
    } else {
        PyErr_SetString(PyExc_IndexError, "Index must be int or string");
        return NULL;
    }
}
コード例 #17
0
static int py_shell_execute(MYX_GRT *grt, const char *linebuf)
{
  node *n;
  MYX_GRT_SHELL_PRIVATE *pshell= grt->shell->data;
  PyObject *result;
  PyObject *mainmod;
  PyObject *globals;

  if (pshell->current_line)
    pshell->current_line= str_g_append(pshell->current_line, linebuf);
  else
    pshell->current_line= g_strdup(linebuf);

  myx_py_acquire(pshell->pycon);

  n= PyParser_SimpleParseStringFlags(pshell->current_line,
                                     Py_single_input,
                                     0);

  if (n && (*linebuf==' ' || *linebuf=='\t'))
  {
    myx_py_release(pshell->pycon);
    return 1;
  }
  if (!n && PyErr_Occurred() && PyErr_ExceptionMatches(PyExc_SyntaxError))
  {
     PyObject *excep;
     PyObject *value;
     PyObject *message;
     PyObject *trace;
     PyErr_Fetch(&excep, &value, &trace);
     Py_DECREF(excep);
     if (trace)
     {
       Py_DECREF(trace);
     }
     message= PyTuple_GetItem(value, 0);
     if (strstr(PyString_AsString(message), "unexpected EOF") || 
        strncmp(PyString_AsString(message), "EOF", 3)==0)
     {
        Py_DECREF(value);
        PyErr_Clear();
        myx_py_release(pshell->pycon);
        return 1;
     }
     Py_DECREF(value);
  }
  
  if (!n)
  {
    PyErr_Print();    

    g_free(pshell->current_line);
    pshell->current_line= NULL;
    
    PyErr_Clear();
    myx_py_release(pshell->pycon);
    return -1;
  }
  PyNode_Free(n);
  PyErr_Clear();

  // command is supposedly complete, try to execute it
  
  mainmod= PyImport_AddModule("__main__");
  if (!mainmod)
  {
    myx_py_release(pshell->pycon);
    return -1;
  }
  globals= PyModule_GetDict(mainmod);
  
  result= PyRun_String(pshell->current_line, Py_single_input, globals, globals);
  
  g_free(pshell->current_line);
  pshell->current_line= NULL;

  if (!result)
  {
    //XXX use myx_grt_prnt to print the exc
    if (PyErr_Occurred())
      PyErr_Print();

    myx_py_release(pshell->pycon);
    
    return -1;
  }
  else
  {
#if notworking
    // attempt to show the result object
    if (result != Py_None)
    {
      PyObject *tmp= PyObject_Str(result);
      if (!tmp)
      {
        PyErr_Clear();
      }
      else
      {
        myx_grt_printf(grt, "%s\n", PyString_AsString(tmp));
      }
      if (tmp)
        Py_DECREF(tmp);
    }
#endif
    Py_DECREF(result);
  }

  myx_py_release(pshell->pycon);
  
  return 0;
}
コード例 #18
0
ファイル: ssdeep.c プロジェクト: 0xDeva/pyssdeep
static PyObject *__pyx_f_6ssdeep_6ssdeep_hash_bytes(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) {
  PyObject *__pyx_v_buf = 0;
  char (*__pyx_v_utext);
  PyObject *__pyx_v_res;
  PyObject *__pyx_r;
  char (*__pyx_1);
  PyObject *__pyx_2 = 0;
  PyObject *__pyx_3 = 0;
  PyObject *__pyx_4 = 0;
  int __pyx_5;
  PyObject *__pyx_6 = 0;
  static char *__pyx_argnames[] = {"buf",0};
  if (!PyArg_ParseTupleAndKeywords(__pyx_args, __pyx_kwds, "O", __pyx_argnames, &__pyx_v_buf)) return 0;
  Py_INCREF(__pyx_v_self);
  Py_INCREF(__pyx_v_buf);
  __pyx_v_res = Py_None; Py_INCREF(__pyx_v_res);

  /* "/home/jose/tmp/ssdeep-2.2/pyssdeep-read-only/ssdeep.pyx":42 */
  __pyx_1 = PyString_AsString(__pyx_v_buf); if (PyErr_Occurred()) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 42; goto __pyx_L1;}
  __pyx_v_utext = __pyx_1;

  /* "/home/jose/tmp/ssdeep-2.2/pyssdeep-read-only/ssdeep.pyx":43 */
  __pyx_2 = __Pyx_GetName(__pyx_b, __pyx_n_len); if (!__pyx_2) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 43; goto __pyx_L1;}
  __pyx_3 = PyTuple_New(1); if (!__pyx_3) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 43; goto __pyx_L1;}
  Py_INCREF(__pyx_v_buf);
  PyTuple_SET_ITEM(__pyx_3, 0, __pyx_v_buf);
  __pyx_4 = PyObject_CallObject(__pyx_2, __pyx_3); if (!__pyx_4) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 43; goto __pyx_L1;}
  Py_DECREF(__pyx_2); __pyx_2 = 0;
  Py_DECREF(__pyx_3); __pyx_3 = 0;
  __pyx_5 = PyInt_AsLong(__pyx_4); if (PyErr_Occurred()) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 43; goto __pyx_L1;}
  Py_DECREF(__pyx_4); __pyx_4 = 0;
  __pyx_2 = PyString_FromString(fuzzy_hash_data(__pyx_v_utext,__pyx_5)); if (!__pyx_2) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 43; goto __pyx_L1;}
  Py_DECREF(__pyx_v_res);
  __pyx_v_res = __pyx_2;
  __pyx_2 = 0;

  /* "/home/jose/tmp/ssdeep-2.2/pyssdeep-read-only/ssdeep.pyx":44 */
  __pyx_5 = PySequence_Contains(__pyx_v_res, __pyx_k5p); if (__pyx_5 < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 44; goto __pyx_L1;}
  if (__pyx_5) {

    /* "/home/jose/tmp/ssdeep-2.2/pyssdeep-read-only/ssdeep.pyx":45 */
    __pyx_3 = __Pyx_GetName(__pyx_m, __pyx_n_SsdeepException); if (!__pyx_3) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 45; goto __pyx_L1;}
    __pyx_4 = __Pyx_GetName(__pyx_b, __pyx_n_replace); if (!__pyx_4) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 45; goto __pyx_L1;}
    __pyx_2 = PyTuple_New(2); if (!__pyx_2) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 45; goto __pyx_L1;}
    Py_INCREF(__pyx_k6p);
    PyTuple_SET_ITEM(__pyx_2, 0, __pyx_k6p);
    Py_INCREF(__pyx_k7p);
    PyTuple_SET_ITEM(__pyx_2, 1, __pyx_k7p);
    __pyx_6 = PyObject_CallObject(__pyx_4, __pyx_2); if (!__pyx_6) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 45; goto __pyx_L1;}
    Py_DECREF(__pyx_4); __pyx_4 = 0;
    Py_DECREF(__pyx_2); __pyx_2 = 0;
    __Pyx_Raise(__pyx_3, __pyx_v_res, __pyx_6);
    Py_DECREF(__pyx_3); __pyx_3 = 0;
    Py_DECREF(__pyx_6); __pyx_6 = 0;
    {__pyx_filename = __pyx_f[0]; __pyx_lineno = 45; goto __pyx_L1;}
    goto __pyx_L2;
  }
  /*else*/ {
    Py_INCREF(__pyx_v_res);
    __pyx_r = __pyx_v_res;
    goto __pyx_L0;
  }
  __pyx_L2:;

  __pyx_r = Py_None; Py_INCREF(__pyx_r);
  goto __pyx_L0;
  __pyx_L1:;
  Py_XDECREF(__pyx_2);
  Py_XDECREF(__pyx_3);
  Py_XDECREF(__pyx_4);
  Py_XDECREF(__pyx_6);
  __Pyx_AddTraceback("ssdeep.ssdeep.hash_bytes");
  __pyx_r = 0;
  __pyx_L0:;
  Py_DECREF(__pyx_v_res);
  Py_DECREF(__pyx_v_self);
  Py_DECREF(__pyx_v_buf);
  return __pyx_r;
}
コード例 #19
0
ファイル: pyvmdk_error.c プロジェクト: talsaiag/libvmdk
/* Fetches an error
 */
void VARARGS(
      pyvmdk_error_fetch,
      libcerror_error_t **error,
      int error_domain,
      int error_code,
      const char *,
      format_string )
{
	va_list argument_list;

	char error_string[ PYVMDK_ERROR_STRING_SIZE ];

        PyObject *exception_traceback = NULL;
        PyObject *exception_type      = NULL;
        PyObject *exception_value     = NULL;
        PyObject *string_object       = NULL;
	static char *function         = "pyvmdk_error_fetch";
	char *exception_string        = NULL;
	size_t error_string_length    = 0;
	int print_count               = 0;

#if PY_MAJOR_VERSION >= 3
	PyObject *utf8_string_object  = NULL;
#endif

	if( format_string == NULL )
	{
		PyErr_Format(
		 PyExc_ValueError,
		 "%s: missing format string.",
		 function );

		return;
	}
	VASTART(
	 argument_list,
	 const char *,
	 format_string );

	print_count = PyOS_vsnprintf(
	               error_string,
	               PYVMDK_ERROR_STRING_SIZE,
	               format_string,
	               argument_list );

	VAEND(
	 argument_list );

	if( print_count < 0 )
	{
		PyErr_Format(
		 PyExc_ValueError,
		 "%s: unable to format error string.",
		 function );

		return;
	}
	error_string_length = libcstring_narrow_string_length(
	                       error_string );

	if( ( error_string_length >= 1 )
	 && ( error_string[ error_string_length - 1 ] == '.' ) )
	{
		error_string[ error_string_length - 1 ] = 0;
	}
	PyErr_Fetch(
	 &exception_type,
	 &exception_value,
	 &exception_traceback );

	string_object = PyObject_Repr(
	                 exception_value );

#if PY_MAJOR_VERSION >= 3
	utf8_string_object = PyUnicode_AsUTF8String(
	                      string_object );

	if( utf8_string_object != NULL )
	{
		exception_string = PyBytes_AsString(
		                    utf8_string_object );
	}
#else
	exception_string = PyString_AsString(
	                    string_object );
#endif
	if( exception_string != NULL )
	{
		libcerror_error_set(
		 error,
		 error_domain,
		 error_code,
		 "%s with error: %s.",
		 error_string,
		 exception_string );
	}
	else
	{
		libcerror_error_set(
		 error,
		 error_domain,
		 error_code,
		 "%s.",
		 error_string );
	}
#if PY_MAJOR_VERSION >= 3
	if( utf8_string_object != NULL )
	{
		Py_DecRef(
		 utf8_string_object );
	}
#endif
	Py_DecRef(
	 string_object );

	return;
}
コード例 #20
0
ファイル: ssdeep.c プロジェクト: 0xDeva/pyssdeep
static PyObject *__pyx_f_6ssdeep_6ssdeep_hash_file(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) {
  PyObject *__pyx_v_filename = 0;
  PyObject *__pyx_v_res;
  PyObject *__pyx_r;
  char (*__pyx_1);
  PyObject *__pyx_2 = 0;
  int __pyx_3;
  PyObject *__pyx_4 = 0;
  PyObject *__pyx_5 = 0;
  PyObject *__pyx_6 = 0;
  static char *__pyx_argnames[] = {"filename",0};
  if (!PyArg_ParseTupleAndKeywords(__pyx_args, __pyx_kwds, "O", __pyx_argnames, &__pyx_v_filename)) return 0;
  Py_INCREF(__pyx_v_self);
  Py_INCREF(__pyx_v_filename);
  __pyx_v_res = Py_None; Py_INCREF(__pyx_v_res);

  /* "/home/jose/tmp/ssdeep-2.2/pyssdeep-read-only/ssdeep.pyx":33 */
  __pyx_1 = PyString_AsString(__pyx_v_filename); if (PyErr_Occurred()) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 33; goto __pyx_L1;}
  __pyx_2 = PyString_FromString(fuzzy_hash(__pyx_1)); if (!__pyx_2) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 33; goto __pyx_L1;}
  Py_DECREF(__pyx_v_res);
  __pyx_v_res = __pyx_2;
  __pyx_2 = 0;

  /* "/home/jose/tmp/ssdeep-2.2/pyssdeep-read-only/ssdeep.pyx":35 */
  __pyx_3 = PySequence_Contains(__pyx_v_res, __pyx_k2p); if (__pyx_3 < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 35; goto __pyx_L1;}
  if (__pyx_3) {

    /* "/home/jose/tmp/ssdeep-2.2/pyssdeep-read-only/ssdeep.pyx":36 */
    __pyx_2 = __Pyx_GetName(__pyx_m, __pyx_n_SsdeepException); if (!__pyx_2) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 36; goto __pyx_L1;}
    __pyx_4 = PyObject_GetAttr(__pyx_v_res, __pyx_n_replace); if (!__pyx_4) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 36; goto __pyx_L1;}
    __pyx_5 = PyTuple_New(2); if (!__pyx_5) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 36; goto __pyx_L1;}
    Py_INCREF(__pyx_k3p);
    PyTuple_SET_ITEM(__pyx_5, 0, __pyx_k3p);
    Py_INCREF(__pyx_k4p);
    PyTuple_SET_ITEM(__pyx_5, 1, __pyx_k4p);
    __pyx_6 = PyObject_CallObject(__pyx_4, __pyx_5); if (!__pyx_6) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 36; goto __pyx_L1;}
    Py_DECREF(__pyx_4); __pyx_4 = 0;
    Py_DECREF(__pyx_5); __pyx_5 = 0;
    __Pyx_Raise(__pyx_2, __pyx_6, 0);
    Py_DECREF(__pyx_2); __pyx_2 = 0;
    Py_DECREF(__pyx_6); __pyx_6 = 0;
    {__pyx_filename = __pyx_f[0]; __pyx_lineno = 36; goto __pyx_L1;}
    goto __pyx_L2;
  }
  /*else*/ {
    Py_INCREF(__pyx_v_res);
    __pyx_r = __pyx_v_res;
    goto __pyx_L0;
  }
  __pyx_L2:;

  __pyx_r = Py_None; Py_INCREF(__pyx_r);
  goto __pyx_L0;
  __pyx_L1:;
  Py_XDECREF(__pyx_2);
  Py_XDECREF(__pyx_4);
  Py_XDECREF(__pyx_5);
  Py_XDECREF(__pyx_6);
  __Pyx_AddTraceback("ssdeep.ssdeep.hash_file");
  __pyx_r = 0;
  __pyx_L0:;
  Py_DECREF(__pyx_v_res);
  Py_DECREF(__pyx_v_self);
  Py_DECREF(__pyx_v_filename);
  return __pyx_r;
}
コード例 #21
0
private int linkgw_create(struct occi_category * optr, void * vptr, struct rest_request * rptr)
{
	struct occi_kind_node * nptr;
	struct linkgw * pptr;
	char sendstr[1024];
	char strtmp[1024];
	char srcdir[1024];
	char * response = NULL;
	char * token;
	FILE * exp_file;
	listcc categoryAtr;
	PyObject    *pName=NULL, *pModule=NULL, *pDict=NULL, *pFunc=NULL,*result=NULL;

	PyThreadState* pythr=NULL;
	if (!( nptr = vptr ))
		return(0);
	else if (!( pptr = nptr->contents ))
		return(0);

	if(!(pptr->name)) strcpy(sendstr," ");
	else if(pptr->name[0]=='\0') strcpy(sendstr," ");
	else strcpy(sendstr,pptr->name);
	if(!(pptr->intercloudGW)){
		strcpy(strtmp," ");
		strConcat(sendstr,strtmp,',');
	}
	else if(pptr->intercloudGW[0]=='\0'){
		strcpy(strtmp," ");
		strConcat(sendstr,strtmp,',');
	}
	else strConcat(sendstr,pptr->intercloudGW,',');
	if(!(pptr->account)){
		strcpy(strtmp," ");
		strConcat(sendstr,strtmp,',');
	}
	else if(pptr->account[0]=='\0'){
		strcpy(strtmp," ");
		strConcat(sendstr,strtmp,',');
	}
	else strConcat(sendstr,pptr->account,',');
	if(!(pptr->gwsrc)){
		strcpy(strtmp," ");
		strConcat(sendstr,strtmp,',');
	}
	else if(pptr->gwsrc[0]=='\0'){
		strcpy(strtmp," ");
		strConcat(sendstr,strtmp,',');
	}
	else strConcat(sendstr,pptr->gwsrc,',');
	if(!(pptr->gwdst)){
		strcpy(strtmp," ");
		strConcat(sendstr,strtmp,',');
	}
	else if(pptr->gwdst[0]=='\0'){
		strcpy(strtmp," ");
		strConcat(sendstr,strtmp,',');
	}
	else strConcat(sendstr,pptr->gwdst,',');
	if(!(pptr->tunnelproto)){
		strcpy(strtmp," ");
		strConcat(sendstr,strtmp,',');
	}
	else if(pptr->tunnelproto[0]=='\0'){
		strcpy(strtmp," ");
		strConcat(sendstr,strtmp,',');
	}
	else strConcat(sendstr,pptr->tunnelproto,',');
	if(!(pptr->addressgresrc)){
		strcpy(strtmp," ");
		strConcat(sendstr,strtmp,',');
	}
	else if(pptr->addressgresrc[0]=='\0'){
		strcpy(strtmp," ");
		strConcat(sendstr,strtmp,',');
	}
	else strConcat(sendstr,pptr->addressgresrc,',');
	if(!(pptr->addressgredst)){
		strcpy(strtmp," ");
		strConcat(sendstr,strtmp,',');
	}
	else if(pptr->addressgredst[0]=='\0'){
		strcpy(strtmp," ");
		strConcat(sendstr,strtmp,',');
	}
	else strConcat(sendstr,pptr->addressgredst,',');
	if(!(pptr->prefix)){
		strcpy(strtmp," ");
		strConcat(sendstr,strtmp,',');
	}
	else if(pptr->prefix[0]=='\0'){
		strcpy(strtmp," ");
		strConcat(sendstr,strtmp,',');
	}
	else strConcat(sendstr,pptr->prefix,',');
	if(!(pptr->authenticationkey)){
		strcpy(strtmp," ");
		strConcat(sendstr,strtmp,',');
	}
	else if(pptr->authenticationkey[0]=='\0'){
		strcpy(strtmp," ");
		strConcat(sendstr,strtmp,',');
	}
	else strConcat(sendstr,pptr->authenticationkey,',');
	if(!(pptr->endpointsrc)){
		strcpy(strtmp," ");
		strConcat(sendstr,strtmp,',');
	}
	else if(pptr->endpointsrc[0]=='\0'){
		strcpy(strtmp," ");
		strConcat(sendstr,strtmp,',');
	}
	else strConcat(sendstr,pptr->endpointsrc,',');
	if(!(pptr->endpointdst)){
		strcpy(strtmp," ");
		strConcat(sendstr,strtmp,',');
	}
	else if(pptr->endpointdst[0]=='\0'){
		strcpy(strtmp," ");
		strConcat(sendstr,strtmp,',');
	}
	else strConcat(sendstr,pptr->endpointdst,',');
	if(!(pptr->state)){
		strcpy(strtmp," ");
		strConcat(sendstr,strtmp,',');
	}
	else if(pptr->state[0]=='\0'){
		strcpy(strtmp," ");
		strConcat(sendstr,strtmp,',');
	}
	else strConcat(sendstr,pptr->state,',');
		//           python interface
		sprintf(srcdir,"%s/pyaccords/pysrc",PYPATH);
		pythr = Py_NewInterpreter();
		python_path(srcdir);
		pName = PyString_FromString("linkgw");
		if(pName == NULL) printf("erro: in linkgw no such file name\n");
		else pModule = PyImport_Import(pName);
		if(pModule == NULL) printf("error: failed to load linkgw module\n");
		else pDict = PyModule_GetDict(pModule);
		if(pDict == NULL) printf("error: failed to load dict name in linkgw module\n");
		else pFunc = PyDict_GetItemString(pDict,"create");
		if(pFunc == NULL) printf("error: failed to load create function in linkgw module\n");
		else result=PyObject_CallFunction(pFunc,"s",sendstr);
		if(result) response=allocate_string(PyString_AsString( result ));
		Py_DECREF(pModule);
		Py_DECREF(pName);
		Py_EndInterpreter(pythr);

	resetListe(&categoryAtr);
	token= strtok(response,",");
	for(; token != NULL ;)
	{
		addBacke(&categoryAtr,token);
		token=strtok(NULL, ",");
	}
	elemm *pelem = categoryAtr.first;
	if(pelem){
		pptr->name = pelem->value;
		pelem = pelem->next;
	}
	if(pelem){
		pptr->intercloudGW = pelem->value;
		pelem = pelem->next;
	}
	if(pelem){
		pptr->account = pelem->value;
		pelem = pelem->next;
	}
	if(pelem){
		pptr->gwsrc = pelem->value;
		pelem = pelem->next;
	}
	if(pelem){
		pptr->gwdst = pelem->value;
		pelem = pelem->next;
	}
	if(pelem){
		pptr->tunnelproto = pelem->value;
		pelem = pelem->next;
	}
	if(pelem){
		pptr->addressgresrc = pelem->value;
		pelem = pelem->next;
	}
	if(pelem){
		pptr->addressgredst = pelem->value;
		pelem = pelem->next;
	}
	if(pelem){
		pptr->prefix = pelem->value;
		pelem = pelem->next;
	}
	if(pelem){
		pptr->authenticationkey = pelem->value;
		pelem = pelem->next;
	}
	if(pelem){
		pptr->endpointsrc = pelem->value;
		pelem = pelem->next;
	}
	if(pelem){
		pptr->endpointdst = pelem->value;
		pelem = pelem->next;
	}
	if(pelem){
		pptr->state = pelem->value;
	}
	return 1;
}
コード例 #22
0
ファイル: libgrowl.c プロジェクト: Dieterbe/dvcs-autosync
static PyObject * growl_PostDictionary(CFStringRef name, PyObject *self, PyObject *args) {
	int i, j;

	PyObject *inputDict;
	PyObject *pKeys = NULL;
	PyObject *pKey, *pValue;

	CFMutableDictionaryRef note = CFDictionaryCreateMutable(kCFAllocatorDefault,
															/*capacity*/ 0,
															&kCFTypeDictionaryKeyCallBacks,
															&kCFTypeDictionaryValueCallBacks);

	if (!PyArg_ParseTuple(args, "O!", &PyDict_Type, &inputDict))
		goto error;

	pKeys = PyDict_Keys(inputDict);
	for (i = 0; i < PyList_Size(pKeys); ++i) {
		CFStringRef convertedKey;

		/* Converting the PyDict key to NSString and used for key in note */
		pKey = PyList_GetItem(pKeys, i);
		if (!pKey)
			// Exception already set
			goto error;
		pValue = PyDict_GetItem(inputDict, pKey);
		if (!pValue) {
			// XXX Neeed a real Error message here.
			PyErr_SetString(PyExc_TypeError," ");
			goto error;
		}
		if (PyUnicode_Check(pKey)) {
			convertedKey = CFStringCreateWithBytes(kCFAllocatorDefault,
												   (const UInt8 *)PyUnicode_AS_DATA(pKey),
												   PyUnicode_GET_DATA_SIZE(pKey),
												   kCFStringEncodingUnicode,
												   false);
		} else if (PyString_Check(pKey)) {
			convertedKey = CFStringCreateWithCString(kCFAllocatorDefault,
													 PyString_AsString(pKey),
													 kCFStringEncodingUTF8);
		} else {
			PyErr_SetString(PyExc_TypeError,"The Dict keys must be strings/unicode");
			goto error;
		}

		/* Converting the PyDict value to NSString or NSData based on class  */
		if (PyString_Check(pValue)) {
			CFStringRef convertedValue = CFStringCreateWithCString(kCFAllocatorDefault,
																   PyString_AS_STRING(pValue),
																   kCFStringEncodingUTF8);
			CFDictionarySetValue(note, convertedKey, convertedValue);
			CFRelease(convertedValue);
		} else if (PyUnicode_Check(pValue)) {
			CFStringRef convertedValue = CFStringCreateWithBytes(kCFAllocatorDefault,
																 (const UInt8 *)PyUnicode_AS_DATA(pValue),
																 PyUnicode_GET_DATA_SIZE(pValue),
																 kCFStringEncodingUnicode,
																 false);
			CFDictionarySetValue(note, convertedKey, convertedValue);
			CFRelease(convertedValue);
		} else if (PyInt_Check(pValue)) {
			long v = PyInt_AS_LONG(pValue);
			CFNumberRef convertedValue = CFNumberCreate(kCFAllocatorDefault,
														kCFNumberLongType,
														&v);
			CFDictionarySetValue(note, convertedKey, convertedValue);
			CFRelease(convertedValue);
		} else if (pValue == Py_None) {
			CFDataRef convertedValue = CFDataCreate(kCFAllocatorDefault, NULL, 0);
			CFDictionarySetValue(note, convertedKey, convertedValue);
			CFRelease(convertedValue);
		} else if (PyList_Check(pValue)) {
			int size = PyList_Size(pValue);
			CFMutableArrayRef listHolder = CFArrayCreateMutable(kCFAllocatorDefault,
																size,
																&kCFTypeArrayCallBacks);
			for (j = 0; j < size; ++j) {
				PyObject *lValue = PyList_GetItem(pValue, j);
				if (PyString_Check(lValue)) {
					CFStringRef convertedValue = CFStringCreateWithCString(kCFAllocatorDefault,
																		   PyString_AS_STRING(lValue),
																		   kCFStringEncodingUTF8);
					CFArrayAppendValue(listHolder, convertedValue);
					CFRelease(convertedValue);
				} else if (PyUnicode_Check(lValue)) {
					CFStringRef convertedValue = CFStringCreateWithBytes(kCFAllocatorDefault,
																		 (const UInt8 *)PyUnicode_AS_DATA(lValue),
																		 PyUnicode_GET_DATA_SIZE(lValue),
																		 kCFStringEncodingUnicode,
																		 false);
					CFArrayAppendValue(listHolder, convertedValue);
					CFRelease(convertedValue);
				} else {
					CFRelease(convertedKey);
					PyErr_SetString(PyExc_TypeError,"The lists must only contain strings");
					goto error;
				}
			}
			CFDictionarySetValue(note, convertedKey, listHolder);
			CFRelease(listHolder);
		} else if (PyObject_HasAttrString(pValue, "rawImageData")) {
			PyObject *lValue = PyObject_GetAttrString(pValue, "rawImageData");
			if (!lValue) {
				goto error;
			} else if (PyString_Check(lValue)) {
				CFDataRef convertedValue = CFDataCreate(kCFAllocatorDefault,
														(const UInt8 *)PyString_AsString(lValue),
														PyString_Size(lValue));
				CFDictionarySetValue(note, convertedKey, convertedValue);
				CFRelease(convertedValue);
			} else {
				CFRelease(convertedKey);
				PyErr_SetString(PyExc_TypeError, "Icon with rawImageData attribute present must ensure it is a string.");
				goto error;
			}
		} else {
			CFRelease(convertedKey);
			PyErr_SetString(PyExc_TypeError, "Value is not of Str/List");
			goto error;
		}
		CFRelease(convertedKey);
	}

	Py_BEGIN_ALLOW_THREADS
	CFNotificationCenterPostNotification(CFNotificationCenterGetDistributedCenter(),
										 /*name*/ name,
										 /*object*/ NULL,
										 /*userInfo*/ note,
										 /*deliverImmediately*/ false);
	CFRelease(note);
	Py_END_ALLOW_THREADS

	Py_DECREF(pKeys);

	Py_INCREF(Py_None);
	return Py_None;

error:
	CFRelease(note);

	Py_XDECREF(pKeys);

	return NULL;
}
コード例 #23
0
/**
 *******************************************************************************************************
 * This function invokes csdk's API's.
 *
 * @param self                  AerospikeClient object
 * @param err                   The as_error to be populated by the function
 *                              with the encountered error if any.
 * @param key                   The C client's as_key that identifies the record.
 * @param py_list               The list containing op, bin and value.
 * @param py_meta               The metadata for the operation.
 * @param operate_policy_p      The value for operate policy.
 *******************************************************************************************************
 */
static
PyObject *  AerospikeClient_Operate_Invoke(
	AerospikeClient * self, as_error *err,
	as_key * key, PyObject * py_list, PyObject * py_meta,
	as_policy_operate * operate_policy_p)
{
	as_val* put_val = NULL;
	char* bin = NULL;
	char* val = NULL;
	long offset = 0;
	double double_offset = 0.0;
	uint32_t ttl = 0;
	long operation = 0;
	int i = 0;
	PyObject * py_rec = NULL;
	PyObject * py_ustr = NULL;
	PyObject * py_ustr1 = NULL;
	PyObject * py_bin = NULL;
	as_record * rec = NULL;

	as_static_pool static_pool;
	memset(&static_pool, 0, sizeof(static_pool));

	as_operations ops;
	Py_ssize_t size = PyList_Size(py_list);
	as_operations_inita(&ops, size);

	if (!self || !self->as) {
		as_error_update(err, AEROSPIKE_ERR_PARAM, "Invalid aerospike object");
		goto CLEANUP;
	}

	if(py_meta) {
		AerospikeClient_CheckForMeta(py_meta, &ops, err);
	}

	if (err->code != AEROSPIKE_OK) {
		goto CLEANUP;
	}

	for ( i = 0; i < size; i++) {
		PyObject * py_val = PyList_GetItem(py_list, i);
		operation = -1;
		offset = 0;
		double_offset = 0.0;
		if ( PyDict_Check(py_val) ) {
			PyObject *key_op = NULL, *value = NULL;
			PyObject * py_value = NULL;
			Py_ssize_t pos = 0;
			while (PyDict_Next(py_val, &pos, &key_op, &value)) {
				if ( ! PyString_Check(key_op) ) {
					as_error_update(err, AEROSPIKE_ERR_CLIENT, "A operation key must be a string.");
					goto CLEANUP;
				} else {
					char * name = PyString_AsString(key_op);
					if(!strcmp(name,"op") && (PyInt_Check(value) || PyLong_Check(value))) {
						operation = PyInt_AsLong(value);
					} else if (!strcmp(name, "bin")) {
						py_bin = value;
					} else if(!strcmp(name, "val")) {
						py_value = value;
					} else {
						as_error_update(err, AEROSPIKE_ERR_PARAM, "operation can contain only op, bin and val keys");
						goto CLEANUP;
					}
				}
			}

			if (py_bin) {
				if (PyUnicode_Check(py_bin)) {
					py_ustr = PyUnicode_AsUTF8String(py_bin);
					bin = PyString_AsString(py_ustr);
				} else if (PyString_Check(py_bin)) {
					bin = PyString_AsString(py_bin);
				} else if (PyByteArray_Check(py_bin)) {
                    bin = PyByteArray_AsString(py_bin);
                } else {
                    as_error_update(err, AEROSPIKE_ERR_PARAM, "Bin name should be of type string");
					goto CLEANUP;
				}

				if (self->strict_types) {
					if (strlen(bin) > AS_BIN_NAME_MAX_LEN) {
						if (py_ustr) {
							Py_DECREF(py_ustr);
							py_ustr = NULL;
						}
						as_error_update(err, AEROSPIKE_ERR_BIN_NAME, "A bin name should not exceed 14 characters limit");
						goto CLEANUP;
					}
				}
			} else if (!py_bin && operation != AS_OPERATOR_TOUCH) {
				as_error_update(err, AEROSPIKE_ERR_PARAM, "Bin is not given");
				goto CLEANUP;
			}
			if (py_value) {
				if (self->strict_types) {
					if (check_type(self, py_value, operation, err)) {
						goto CLEANUP;
					}
				}
			} else if ((!py_value) && (operation != AS_OPERATOR_READ && operation != AS_OPERATOR_TOUCH)) {
				as_error_update(err, AEROSPIKE_ERR_PARAM, "Value should be given");
				goto CLEANUP;
			}

			switch(operation) {
				case AS_OPERATOR_APPEND:
					if (PyUnicode_Check(py_value)) {
						py_ustr1 = PyUnicode_AsUTF8String(py_value);
						val = PyString_AsString(py_ustr1);
						as_operations_add_append_str(&ops, bin, val);
					} else if (PyString_Check(py_value)) {
						val = PyString_AsString(py_value);
						as_operations_add_append_str(&ops, bin, val);
					} else if (PyByteArray_Check(py_value)) {
						as_bytes *bytes;
						GET_BYTES_POOL(bytes, &static_pool, err);
						serialize_based_on_serializer_policy(self, SERIALIZER_PYTHON, &bytes, py_value, err);
						as_operations_add_append_raw(&ops, bin, bytes->value, bytes->size);
					} else {
						if (!self->strict_types || !strcmp(py_value->ob_type->tp_name, "aerospike.null")) {
							as_operations *pointer_ops = &ops;
							as_binop *binop = &pointer_ops->binops.entries[pointer_ops->binops.size++];
							binop->op = AS_OPERATOR_APPEND;
							initialize_bin_for_strictypes(self, err, py_value, binop, bin, &static_pool);
						}
					}
					break;
				case AS_OPERATOR_PREPEND:
					if (PyUnicode_Check(py_value)) {
						py_ustr1 = PyUnicode_AsUTF8String(py_value);
						val = PyString_AsString(py_ustr1);
						as_operations_add_prepend_str(&ops, bin, val);
					} else if (PyString_Check(py_value)) {
						val = PyString_AsString(py_value);
						as_operations_add_prepend_str(&ops, bin, val);
					} else if (PyByteArray_Check(py_value)) {
						as_bytes *bytes;
						GET_BYTES_POOL(bytes, &static_pool, err);
						serialize_based_on_serializer_policy(self, SERIALIZER_PYTHON, &bytes, py_value, err);
						as_operations_add_prepend_raw(&ops, bin, bytes->value, bytes->size);
					} else {
						if (!self->strict_types || !strcmp(py_value->ob_type->tp_name, "aerospike.null")) {
							as_operations *pointer_ops = &ops;
							as_binop *binop = &pointer_ops->binops.entries[pointer_ops->binops.size++];
							binop->op = AS_OPERATOR_PREPEND;
							initialize_bin_for_strictypes(self, err, py_value, binop, bin, &static_pool);
						}
					}
					break;
				case AS_OPERATOR_INCR:
					if (PyInt_Check(py_value)) {
						offset = PyInt_AsLong(py_value);
						as_operations_add_incr(&ops, bin, offset);
					} else if ( PyLong_Check(py_value) ) {
						offset = PyLong_AsLong(py_value);
						if (offset == -1 && PyErr_Occurred()) {
							if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
								as_error_update(err, AEROSPIKE_ERR_PARAM, "integer value exceeds sys.maxsize");
								goto CLEANUP;
							}
						}
						as_operations_add_incr(&ops, bin, offset);
					} else if (PyFloat_Check(py_value)) {
						double_offset = PyFloat_AsDouble(py_value);
						as_operations_add_incr_double(&ops, bin, double_offset);
					} else {
						if (!self->strict_types || !strcmp(py_value->ob_type->tp_name, "aerospike.null")) {
							as_operations *pointer_ops = &ops;
							as_binop *binop = &pointer_ops->binops.entries[pointer_ops->binops.size++];
							binop->op = AS_OPERATOR_INCR;
							initialize_bin_for_strictypes(self, err, py_value, binop, bin, &static_pool);
						}
					}
					break;
				case AS_OPERATOR_TOUCH:
                    ops.ttl = 0;
					if (py_value && PyInt_Check(py_value)) {
                        ops.ttl = PyInt_AsLong(py_value);
                    } else if (py_value && PyLong_Check(py_value)) {
                        ttl = PyLong_AsLong(py_value);
                        if((uint32_t)-1 == ttl) {
                            as_error_update(err, AEROSPIKE_ERR_PARAM, "integer value for ttl exceeds sys.maxsize");
                            goto CLEANUP;
                        }
                        ops.ttl = ttl;
                    }
					as_operations_add_touch(&ops);
					break;
				case AS_OPERATOR_READ:
					as_operations_add_read(&ops, bin);
					break;
				case AS_OPERATOR_WRITE:
					pyobject_to_astype_write(self, err, bin, py_value, &put_val, &ops,
							&static_pool, SERIALIZER_PYTHON);
					if (err->code != AEROSPIKE_OK) {
						goto CLEANUP;
					}
					as_operations_add_write(&ops, bin, (as_bin_value *) put_val);
					break;
				default:
					if (self->strict_types) {
						as_error_update(err, AEROSPIKE_ERR_PARAM, "Invalid operation given");
						goto CLEANUP;
					}
			}
		}
	}

	// Initialize record
	as_record_init(rec, 0);

	Py_BEGIN_ALLOW_THREADS
	aerospike_key_operate(self->as, err, operate_policy_p, key, &ops, &rec);
	Py_END_ALLOW_THREADS

	if (err->code != AEROSPIKE_OK) {
		as_error_update(err, err->code, NULL);
		goto CLEANUP;
	}
	if(rec) {
		record_to_pyobject(self, err, rec, key, &py_rec);
	}

CLEANUP:
	if (py_ustr) {
		Py_DECREF(py_ustr);
	}
	if (py_ustr1) {
		Py_DECREF(py_ustr1);
	}
	if (rec) {
		as_record_destroy(rec);
	}
	if (key->valuep) {
		as_key_destroy(key);
	}
	if (put_val) {
		as_val_destroy(put_val);
	}

	if ( err->code != AEROSPIKE_OK ) {
		PyObject * py_err = NULL;
		error_to_pyobject(err, &py_err);
		PyObject *exception_type = raise_exception(err);
		PyErr_SetObject(exception_type, py_err);
		Py_DECREF(py_err);
		return NULL;
	}

	if (py_rec) {
		return py_rec;
	} else {
		return PyLong_FromLong(0);
	}
}
コード例 #24
0
ファイル: cls_example.cpp プロジェクト: AutumnLight/orange
bool convertFromPythonExisting(PyObject *lst, TExample &example)
{
  PDomain dom=example.domain;

  if (PyOrExample_Check(lst)) {
    const TExample &orex = PyExample_AS_ExampleReference(lst);
    if (orex.domain != dom)
      dom->convert(example, orex);
    else
      example = orex;
    return true;
  }

  if (!PyList_Check(lst)) {
    PyErr_Format(PyExc_TypeError, "invalid argument type (expected list, got '%s)", lst ? lst->ob_type->tp_name : "None");
    return false;
  }

  int const nvars = dom->variables->size() + dom->classVars->size();
  if (Py_ssize_t(nvars) != PyList_Size(lst)) {
    PyErr_Format(PyExc_IndexError, "invalid list size (got %i, expected %i items)",
        PyList_Size(lst), nvars);
    return false;
  }

  Py_ssize_t pos = 0;
  TExample::iterator ei(example.begin());
  TVarList::iterator vi(dom->variables->begin());
  TVarList::const_iterator const ve(dom->variables->end());
  TVarList::const_iterator const ce(dom->classVars->end());
  while(vi != ce && vi != ve) {
    PyObject *li=PyList_GetItem(lst, pos++);
    if (!li)
      PYERROR(PyExc_SystemError, "can't read the list", false);

    if (PyOrValue_Check(li))
      if (PyValue_AS_Variable(li) ? (PyValue_AS_Variable(li) != *vi) : (PyValue_AS_Value(li).varType=!(*vi)->varType) ) {
        PyErr_Format(PyExc_TypeError, "wrong value type for attribute no. %i (%s)", pos, (*vi)->get_name().c_str());
        return false;
      }
      else
        *(ei++)=PyValue_AS_Value(li);

    else {
      if (li == Py_None) {
        *(ei++) = (*vi)->DK();
      } else if (PyString_Check(li)) {
          (*vi)->str2val(string(PyString_AsString(li)), *(ei++));
      } else if ((*vi)->varType==TValue::INTVAR) {
        if (PyInt_Check(li)) {
          TEnumVariable * enumvar = dynamic_cast<TEnumVariable *>(vi->getUnwrappedPtr());
          int value = int(PyInt_AsLong(li));
          if (value < 0 || value >= enumvar->noOfValues()) {
            PyErr_Format(PyExc_ValueError,
                         "value index %i out of range (0 - %i) at attribute no %i (%s)",
                         value, enumvar->noOfValues() - 1, pos, enumvar->get_name().c_str());
            return false;
          }
          *(ei++) = TValue(value);
        } else {
          PyErr_Format(PyExc_TypeError, "attribute no. %i (%s) is ordinal, string or int value expected", pos, (*vi)->get_name().c_str());
          return false;
        }
      }
      else if ((*vi)->varType==TValue::FLOATVAR) {
        float f;
        if (PyNumber_ToFloat(li, f))
          *(ei++) = TValue(f);
        else {
          PyErr_Format(PyExc_TypeError, "attribute no. %i (%s) is continuous, float value expected", pos, (*vi)->get_name().c_str());
          return false;
        }
      }
      else
        ei++;
    }
    if (++vi == ve) {
        vi = dom->classVars->begin();
    }
  }

  return true;
}
コード例 #25
0
ファイル: _common.c プロジェクト: aszeszo/test
/*ARGSUSED*/
static inline PyObject *
_generic_init_common(PyObject *action, PyObject *data, PyObject *attrs)
{
	PyObject *key_aname = NULL;
	PyObject *key_attr = NULL;
	PyObject *path_attr = NULL;
	char *path = NULL;
	char invalid_path = 0;

	/*
	 * Before doing anything else to the action, action attributes must be
	 * set as set_data() relies on it.
	 */
	if (attrs != NULL) {
		if (PyObject_SetAttrString(action, "attrs", attrs) == -1)
			return (NULL);
	} else {
		/* Caller didn't specify any keyword arguments. */
		if ((attrs = PyDict_New()) == NULL)
			return (NULL);
		if (PyObject_SetAttrString(action, "attrs", attrs) == -1) {
			Py_DECREF(attrs);
			return (NULL);
		}
		Py_DECREF(attrs);
	}

	if (data == NULL || data == Py_None) {
		/* No need to call set_data(); this is much faster. */
		if (PyObject_SetAttrString(action, "data", Py_None) == -1)
			return (NULL);
	} else {
		PyObject *res = PyObject_CallMethod(action, "set_data", "(O)",
		    data);
		if (res == NULL)
			return (NULL);
		Py_DECREF(res);
	}

	if ((key_aname = PyObject_GetAttrString(action, "key_attr")) == NULL)
		return (NULL);

	if (key_aname == Py_None) {
		Py_DECREF(key_aname);
		Py_RETURN_NONE;
	}

	if ((key_attr = PyDict_GetItem(attrs, key_aname)) == NULL) {
		PyObject *aname = PyObject_GetAttrString(action, "name");
		char *ns = PyString_AS_STRING(aname);

		/*
		 * set actions allow an alternate value form, so
		 * AttributeAction.__init__ will fill this in later and raise an
		 * exception if appropriate.
		 *
		 * signature actions can't require their key attribute since the
		 * value of a signature may not yet be known.
		 */
		if (strcmp(ns, "set") != 0 && strcmp(ns, "signature") != 0) {
			set_invalid_action_error("MissingKeyAttributeError",
			    action, key_aname);
			Py_DECREF(key_aname);
			return (NULL);
		}

		Py_DECREF(key_aname);
		Py_RETURN_NONE;
	}

	if (PyList_CheckExact(key_attr)) {
		PyObject *aname = PyObject_GetAttrString(action, "name");
		char *ns = PyString_AS_STRING(aname);
		int multi_error = 0;

		if (strcmp(ns, "depend") != 0) {
			/*
			 * Unless this is a dependency action, multiple values
			 * are never allowed for key attribute.
			 */
			multi_error = 1;
		} else {
			PyObject *dt = PyDict_GetItemString(attrs, "type");
			/*
			 * If dependency type is 'require-any', multiple values
			 * are allowed for key attribute.
			 */
			if (dt != NULL) {
				char *ts = PyString_AsString(dt);
				if (ts == NULL) {
					Py_DECREF(key_aname);
					Py_DECREF(aname);
					return (NULL);
				}
				if (strcmp(ts, "require-any") != 0)
					multi_error = 1;
			} else {
				multi_error = 1;
			}
		}

		Py_DECREF(aname);
		if (multi_error == 1) {
			set_invalid_action_error("KeyAttributeMultiValueError",
			    action, key_aname);
			Py_DECREF(key_aname);
			return (NULL);
		}
	}

	if ((path_attr = PyDict_GetItemString(attrs, "path")) == NULL) {
		Py_DECREF(key_aname);
		Py_RETURN_NONE;
	}

	if ((path = PyString_AsString(path_attr)) != NULL) {
		if (path[0] == '/') {
			PyObject *stripped = PyObject_CallMethod(
			    path_attr, "lstrip", "(s)", "/");
			if (stripped == NULL) {
				Py_DECREF(key_aname);
				return (NULL);
			}
			if (PyDict_SetItemString(attrs, "path",
			    stripped) == -1) {
				Py_DECREF(key_aname);
				Py_DECREF(stripped);
				return (NULL);
			}
			if (PyString_GET_SIZE(stripped) == 0)
				invalid_path = 1;
			Py_DECREF(stripped);
		} else {
			if (PyString_GET_SIZE(path_attr) == 0)
				invalid_path = 1;
		}
	} else {
		/* path attribute is not a string. */
		invalid_path = 1;
	}

	if (invalid_path == 1) {
		set_invalid_action_error("InvalidPathAttributeError",
		    action, key_aname);
		Py_DECREF(key_aname);
		return (NULL);
	}

	Py_DECREF(key_aname);
	Py_RETURN_NONE;
}
コード例 #26
0
ファイル: command.c プロジェクト: CasaMallo/twopence
/*
 * Initialize the command object
 *
 * Typical ways to do this include
 *    cmd = twopence.Command("/bin/ls", user = "******", stdout = bytearray());
 *    cmd = twopence.Command("/bin/ls", user = "******", stdout = str());
 *    cmd = twopence.Command("/usr/bin/wc", stdin = "/etc/hosts");
 */
int
Command_init(twopence_Command *self, PyObject *args, PyObject *kwds)
{
	static char *kwlist[] = {
		"command",
		"user",
		"timeout",
		"stdin",
		"stdout",
		"stderr",
		"suppressOutput",
		"quiet",
		"background",
		NULL
	};
	PyObject *stdinObject = NULL, *stdoutObject = NULL, *stderrObject = NULL;
	char *command, *user = NULL;
	long timeout = 0L;
	int quiet = 0;
	int background = 0;

	if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|slOOOiii", kwlist,
				&command, &user, &timeout, &stdinObject, &stdoutObject, &stderrObject,
				&quiet, &quiet,
				&background))
		return -1;

	self->command = twopence_strdup(command);
	self->user = user? twopence_strdup(user) : NULL;
	self->timeout = timeout? timeout: 60L;
	self->stdout = NULL;
	self->stderr = NULL;
	self->stdinPath = NULL;
	self->stdin = NULL;
	self->quiet = quiet;
	self->background = background;

	if (stdoutObject == NULL) {
		stdoutObject = twopence_callType(&PyByteArray_Type, NULL, NULL);
	} else {
		Py_INCREF(stdoutObject);
	}
	self->stdout = stdoutObject;

	if (stderrObject == NULL)
		stderrObject = stdoutObject;

	Py_INCREF(stderrObject);
	self->stderr = stderrObject;

	if (stdinObject == NULL || stdinObject == Py_None) {
		/* Do not pipe any input to the command */
	} else
	if (PyString_Check(stdinObject)) {
		char *s;

		if ((s = PyString_AsString(stdinObject)) == NULL)
			return -1;
		self->stdinPath = twopence_strdup(s);
	} else {
		Py_INCREF(stdinObject);
		self->stdin = stdinObject;
	}

	return 0;
}
コード例 #27
0
bool PythonScript::compile(bool for_eval)
{
	// Support for the convenient col() and cell() functions.
	// This can't be done anywhere else, because we need access to the local
	// variables self, i and j.
	if(Context->inherits("Table")) {
		// A bit of a hack, but we need either IndexError or len() from __builtins__.
		PyDict_SetItemString(localDict, "__builtins__",
				PyDict_GetItemString(env()->globalDict(), "__builtins__"));
		PyObject *ret = PyRun_String(
				"def col(c,*arg):\n"
				"\ttry: return self.cell(c,arg[0])\n"
				"\texcept(IndexError): return self.cell(c,i)\n"
				"def cell(c,r):\n"
				"\treturn self.cell(c,r)\n"
				"def tablecol(t,c):\n"
				"\treturn self.folder().rootFolder().table(t,True).cell(c,i)\n"
				"def _meth_table_col_(t,c):\n"
				"\treturn t.cell(c,i)\n"
				"self.__class__.col = _meth_table_col_",
				Py_file_input, localDict, localDict);
		if (ret)
			Py_DECREF(ret);
		else
			PyErr_Print();
	} else if(Context->inherits("Matrix")) {
		// A bit of a hack, but we need either IndexError or len() from __builtins__.
		PyDict_SetItemString(localDict, "__builtins__",
				PyDict_GetItemString(env()->globalDict(), "__builtins__"));
		PyObject *ret = PyRun_String(
				"def cell(*arg):\n"
				"\ttry: return self.cell(arg[0],arg[1])\n"
				"\texcept(IndexError): return self.cell(i,j)\n",
				Py_file_input, localDict, localDict);
		if (ret)
			Py_DECREF(ret);
		else
			PyErr_Print();
	}
	bool success=false;
	Py_XDECREF(PyCode);
	// Simplest case: Code is a single expression
	PyCode = Py_CompileString(Code, Name, Py_eval_input);

	if (PyCode)
		success = true;
	else if (for_eval) {
		// Code contains statements (or errors) and we want to get a return
		// value from it.
		// So we wrap the code into a function definition,
		// execute that (as Py_file_input) and store the function object in PyCode.
		// See http://mail.python.org/pipermail/python-list/2001-June/046940.html
		// for why there isn't an easier way to do this in Python.
		PyErr_Clear(); // silently ignore errors
		PyObject *key, *value;
#if PY_VERSION_HEX >= 0x02050000
		Py_ssize_t i=0;
#else
		int i=0;
#endif
		QString signature = "";
		while(PyDict_Next(localDict, &i, &key, &value))
			signature.append(PyString_AsString(key)).append(",");
		signature.truncate(signature.length()-1);
		QString fdef = "def __doit__("+signature+"):\n";
		fdef.append(Code);
		fdef.replace('\n',"\n\t");
		PyCode = Py_CompileString(fdef, Name, Py_file_input);
		if (PyCode){
			PyObject *tmp = PyDict_New();
			Py_XDECREF(PyEval_EvalCode((PyCodeObject*)PyCode, env()->globalDict(), tmp));
			Py_DECREF(PyCode);
			PyCode = PyDict_GetItemString(tmp,"__doit__");
			Py_XINCREF(PyCode);
			Py_DECREF(tmp);
		}
		success = (PyCode != NULL);
	} else {
		// Code contains statements (or errors), but we do not need to get
		// a return value.
		PyErr_Clear(); // silently ignore errors
		PyCode = Py_CompileString(Code, Name, Py_file_input);
		success = (PyCode != NULL);
	}

	if (!success){
		compiled = compileErr;
		emit_error(env()->errorMsg(), 0);
	} else
		compiled = isCompiled;
	return success;
}
コード例 #28
0
static PyObject *
process_task(PyObject *self, PyObject *args)
{
	//printf ("####C#### PROCESS TASK\n");

	long app_id = PyInt_AsLong(PyTuple_GetItem(args, 0));
	//printf ("####C####App id: %ld\n", app_id);
	char *path = PyString_AsString(PyTuple_GetItem(args, 1));
	//printf ("####C####Path: %s\n", path);
	char *func_name = PyString_AsString(PyTuple_GetItem(args, 2));
	//printf ("####C####Function name: %s\n", func_name);
	int priority = (int)PyInt_AsLong(PyTuple_GetItem(args, 3));
	//printf ("####C####Priority: %d\n", priority);
	int has_target = (int)PyInt_AsLong(PyTuple_GetItem(args, 4));
	//printf ("####C####Has target: %d\n", has_target);

	PyObject *values = PyList_AsTuple(PyTuple_GetItem(args, 5));
	PyObject *compss_types = PyList_AsTuple(PyTuple_GetItem(args, 6));
	PyObject *compss_directions = PyList_AsTuple(PyTuple_GetItem(args, 7));
	Py_ssize_t num_pars = PyTuple_Size(values);
	//printf ("####C####Num pars: %d\n", num_pars);

	PyObject *type, *val, *direction;

	Py_ssize_t j, pj;
    long l;
    int i;
    double d;
    char *s;

    void **params[num_pars * 3];
    int c_types[num_pars], c_directions[num_pars];
    char *c_values, *ini_c_values;

    int val_size = 0;

    // Get C types and directions
    for (j = 0; j < num_pars; j++) {
    	type = PyTuple_GetItem(compss_types, j); // this does not increment reference (we don't own it) so no need for decref
    	direction = PyTuple_GetItem(compss_directions, j);

    	c_types[j] = (int)PyInt_AsLong(type);
    	c_directions[j] = (int)PyInt_AsLong(direction);
    	switch ((enum datatype) c_types[j]) {
    		case file_dt:
    			val_size += sizeof(char*);
    			break;
    	    case string_dt:
    	    	val_size += sizeof(char*);
    			break;
    	    case int_dt:
    	    	val_size += sizeof(int);
    	        break;
    	    case long_dt:
    	    	val_size += sizeof(long);
    	        break;
    	    case double_dt:
    	    	val_size += sizeof(double);
    	        break;
    		case boolean_dt:
    			val_size += sizeof(int);
    			break;
     		default:
     			break;
        }
    }

    //printf ("####C####Size of values: %d\n", val_size);

    // Build the C values
    //c_values = (char *)malloc(val_size);
    c_values = (char *)PyMem_Malloc(val_size); // allocate the memory in the Python heap
    ini_c_values = c_values;
    for (j = 0; j < num_pars; j++) {
    	pj = j * 3;
    	val = PyTuple_GetItem(values, j); // this does not increment reference (we don't own it) so no need for decref
    	params[pj] = (void *)c_values;
    	switch ((enum datatype) c_types[j]) {
    		case file_dt:
    			s = PyString_AsString(val);
    			*(char**)c_values = s;
    			//printf ("####C#### \t Arg %d (FILE): %s, add %ld\n", j, *(char**)c_values, c_values);
    			c_values += sizeof(char*);
    			break;
    	    case string_dt:
    	    	s = PyString_AsString(val);
    	    	*(char**)c_values = s;
    	    	//printf ("####C#### \t Arg %d (STRING): %s, add %ld\n", j, *(char**)c_values, c_values);
    	    	c_values += sizeof(char*);
    	        break;
    	    case int_dt:
    	    	i = (int)PyInt_AsLong(val);
    	    	*(int*)c_values = i;
    	    	//printf ("####C#### \t Arg %d (INT): %d, add %ld\n", j, *(int*)c_values, c_values);
    	    	c_values += sizeof(int);
    	        break;
    	    case long_dt:
    	    	l = PyLong_AsLong(val);
    	    	*(long*)c_values = l;
    	    	//printf ("####C#### \t Arg %d (LONG): %ld, add %ld\n", j, *(long*)c_values, c_values);
    	    	c_values += sizeof(long);
    	        break;
    	    case double_dt:
    	    	d = PyFloat_AsDouble(val);
				*(double*)c_values = d;
				//printf ("####C#### \t Arg %d (FLOAT): %f, add %ld\n", j, *(double *)c_values, c_values);
				c_values += sizeof(double);
				break;
    	    case boolean_dt:
    			i = (int)PyInt_AsLong(val);
    			*(int*)c_values = i;
    			//printf ("####C#### \t Arg %d (BOOL): %d, add %ld\n", j, *(int*)c_values, c_values);
    			c_values += sizeof(int);
    			break;
    		default:
    			break;
    	}
    	params[pj+1] = (void *)&c_types[j];
    	params[pj+2] = (void *)&c_directions[j];
    }

    // Invoke the C library
    GS_ExecuteTask(app_id,
    			   path, // class_name
    			   func_name, // method_name
    			   priority,
    			   has_target,
    			   (int)num_pars,
    			   params);

    //free(c_values);
    PyMem_Free(ini_c_values);

    Py_DECREF(values);
    Py_DECREF(compss_types);
    Py_DECREF(compss_directions);

    return Py_BuildValue("i", 0);
}
コード例 #29
0
ファイル: SpyceModule.cpp プロジェクト: flyingtime/boxee
	int spyceRequest(webs_t wp, char_t *lpath)
	{
		// initialize python first
		if(!spyInitialized)
		{
			g_pythonParser.Initialize();

			PyEval_AcquireLock();
			PyInterpreterState * mainInterpreterState = g_pythonParser.getMainThreadState()->interp;
			spyThreadState = PyThreadState_New(mainInterpreterState);
			PyThreadState_Swap(spyThreadState);

			PyObject* pName = PyString_FromString("spyceXbmc");
			PyObject* pModule = PyImport_Import(pName);
			Py_XDECREF(pName);

			if(!pModule) websError(wp, 500, (char*)"%s", (char*)"Corrupted Spyce installation");
			else
			{
				PyObject* pDict = PyModule_GetDict(pModule);
				Py_XDECREF(pModule);
				spyFunc = PyDict_GetItemString(pDict, "ParseFile");
				if(!spyFunc) websError(wp, 500, (char*)"%s", (char*)"Corrupted Spyce installation");
				
				else spyInitialized = true;
			}

			PyThreadState_Swap(NULL);
			PyEval_ReleaseLock();
			if(!spyInitialized)
			{
				PyThreadState_Clear(spyThreadState);
				PyThreadState_Delete(spyThreadState);
				g_pythonParser.Finalize();
				return -1;		
			}
			
		}

		PyEval_AcquireLock();
		PyThreadState_Swap(spyThreadState);

		std::string strRequestMethod;
		std::string strQuery = wp->query;
		std::string strCookie;
		int iContentLength = 0;
		
		if (strlen(wp->query) > 0)
		{
			if(wp->flags & WEBS_POST_REQUEST)	strRequestMethod = "POST";
			else if (wp->flags & WEBS_HEAD_REQUEST) strRequestMethod = "HEAD";
			else strRequestMethod = "GET";
		}

		if (wp->flags & WEBS_COOKIE) strCookie = wp->cookie;
		iContentLength = strQuery.length();

		// create enviroment and parse file
		PyObject* pEnv = PyDict_New();
		PyObject* pREQUEST_METHOD = PyString_FromString(strRequestMethod.c_str());
		PyObject* pCONTENT_LENGTH = PyInt_FromLong(iContentLength);
		PyObject* pQUERY_STRING = PyString_FromString(strQuery.c_str());
		PyObject* pHTTP_COOKIE = PyString_FromString(strCookie.c_str());
		PyObject* pCONTENT_TYPE = PyString_FromString(wp->type);
		PyObject* pHTTP_HOST = PyString_FromString(wp->host);
		PyObject* pHTTP_USER_AGENT = PyString_FromString(wp->userAgent ? wp->userAgent : "");
		PyObject* pHTTP_CONNECTION = PyString_FromString((wp->flags & WEBS_KEEP_ALIVE)? "Keep-Alive" : "");

		PyDict_SetItemString(pEnv, "REQUEST_METHOD", pREQUEST_METHOD);
		PyDict_SetItemString(pEnv, "CONTENT_LENGTH", pCONTENT_LENGTH);
		PyDict_SetItemString(pEnv, "QUERY_STRING", pQUERY_STRING);
		PyDict_SetItemString(pEnv, "HTTP_COOKIE", pHTTP_COOKIE);
		//PyDict_SetItemString(pEnv, "CONTENT_TYPE", pCONTENT_TYPE);
		PyDict_SetItemString(pEnv, "HTTP_HOST", pHTTP_HOST);
		PyDict_SetItemString(pEnv, "HTTP_USER_AGENT", pHTTP_USER_AGENT);
		PyDict_SetItemString(pEnv, "HTTP_CONNECTION", pHTTP_CONNECTION);

		PyObject* pResult = PyObject_CallFunction(spyFunc, (char*)"sO", lpath, pEnv);

		Py_XDECREF(pREQUEST_METHOD);
		Py_XDECREF(pCONTENT_LENGTH);
		Py_XDECREF(pQUERY_STRING);
		Py_XDECREF(pHTTP_COOKIE);
		Py_XDECREF(pCONTENT_TYPE);
		Py_XDECREF(pHTTP_HOST);
		Py_XDECREF(pHTTP_USER_AGENT);
		Py_XDECREF(pHTTP_CONNECTION);

		Py_XDECREF(pEnv);

		if(!pResult) websError(wp, 500, (char*)"%s", (char*)"Corrupted Spyce installation");
		else
		{
			char* cResult = PyString_AsString(pResult);
			websWriteBlock(wp, cResult, strlen(cResult));
			Py_XDECREF(pResult);
		}

		PyThreadState_Swap(NULL);
		PyEval_ReleaseLock();

	/*
	*	Common exit and cleanup
	*/
		if (websValid(wp)) {
			websPageClose(wp);
		}
		return 0;
	}
コード例 #30
0
int c_function(int *n, float **mat)
{
  PyObject *pModule  = NULL;
  PyObject *pFunc = NULL;
  PyObject *pArg = NULL;
  PyObject *pRet = NULL;
  PyObject *pName = NULL;

  size_t size = *n;
  npy_intp *dim;
  int i, j;

  dim = (npy_intp *) malloc(sizeof(npy_intp)*(size));

  for (i=0; i < size; i++) dim[i] = size;

  Py_Initialize();

  if (!Py_IsInitialized())
  {
    fprintf(stderr, "nao foi possivel inicializar o python!\n");
    return -1;
  }

  init_numpy(); 

  PyObject* pMat = PyArray_NewFromDescr(
     &PyArray_Type, PyArray_DescrFromType(NPY_FLOAT), 
     2, dim, NULL, (void *) *mat, NPY_ARRAY_INOUT_FARRAY, NULL);

  Py_INCREF(pMat);

  pName = PyString_FromString("function");
  pModule = PyImport_Import(pName);

  pFunc = PyObject_GetAttrString(pModule, "py_function");

  if(!PyCallable_Check(pFunc))
  {
    printf("func not callable!\n");
    return -1;
  }

  pArg = PyTuple_New (2);
  PyTuple_SetItem(pArg, 0, (PyObject *) PyInt_FromLong(size));
  PyTuple_SetItem(pArg, 1, pMat);

  pRet = PyObject_CallObject(pFunc, pArg);

  printf("py ret: %s\n", PyString_AsString(pRet));

  Py_DECREF (pMat);
  Py_DECREF (pName);
  Py_DECREF (pModule);
  Py_DECREF (pFunc);
  Py_DECREF (pArg);
  Py_DECREF (pRet);

  Py_Finalize();

  return 0;
}