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

C++ PyString_AsString函数代码示例

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

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



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

示例1: pydc_call

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 );
//.........这里部分代码省略.........
开发者ID:svn2github,项目名称:dyncall,代码行数:101,代码来源:pydcext.c


示例2: Snmp_op

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;
//.........这里部分代码省略.........
开发者ID:arielsalvo,项目名称:wiremaps,代码行数:101,代码来源:snmp.c


示例3: AerospikeQuery_Select

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;
}
开发者ID:Kavec,项目名称:aerospike-client-python,代码行数:63,代码来源:select.c


示例4: initialize_bin_for_strictypes

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);
}
开发者ID:minewhat,项目名称:aerospike-client-python,代码行数:73,代码来源:operate.c


示例5: print_string_repr

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;
}
开发者ID:jon-turney,项目名称:binutils-gdb,代码行数:77,代码来源:py-prettyprint.c


示例6: PyEval_AcquireLock

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);

//.........这里部分代码省略.........
开发者ID:AWilco,项目名称:xbmc,代码行数:101,代码来源:XBPyThread.cpp


示例7: PyEval_AcquireLock

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);

//.........这里部分代码省略.........
开发者ID:Jdad,项目名称:xbmc,代码行数:101,代码来源:XBPyThread.cpp


示例8: __parse_resource

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;
}
开发者ID:edwardbadboy,项目名称:sanlock-ubuntu,代码行数:66,代码来源:sanlock.c


示例9: py_execute


//.........这里部分代码省略.........
        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;
}
开发者ID:dhirajkhatiwada1,项目名称:uludag,代码行数:101,代码来源:script.c


示例10: Xine_Post_PyObject_set_parameters

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;
}
开发者ID:clones,项目名称:kaa,代码行数:83,代码来源:post.c


示例11: PyErr_Format

/* 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 );

//.........这里部分代码省略.........
开发者ID:zhangway100,项目名称:libewf,代码行数:101,代码来源:pyewf_file_entry.c


示例12: Frame_Convert

// ---------------------------------------------------------------------------------
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++ )
//.........这里部分代码省略.........
开发者ID:audioburn,项目名称:pymedia-redux-full,代码行数:101,代码来源:vcodec.c


示例13: convertsimple1

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,
//.........这里部分代码省略.........
开发者ID:Claruarius,项目名称:stblinux-2.6.37,代码行数:101,代码来源:getargs.c


示例14: myx_py_get_grt

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;
}
开发者ID:cyberbeat,项目名称:mysql-gui-tools,代码行数:66,代码来源:myx_grt_python_shell.c


示例15: pysqlite_row_subscript

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;
    }
}
开发者ID:1310701102,项目名称:sl4a,代码行数:68,代码来源:row.c


示例16: py_shell_execute

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_ 

鲜花

握手

雷人

路过

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

请发表评论

全部评论

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

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

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

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

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