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

C++ PyObject_CallMethod函数代码示例

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

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



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

示例1: import_array

// * GCHMCIntegrator Constructor * //
GCHMCIntegrator::GCHMCIntegrator(PyObject *universe, std::string ligdir, std::string gaff_fn)
{
  std::cout<<"GCHMCIntegrator instance created 20160826"<<std::endl;
  import_array();

  temperature = 300.0;
  delta_t = 0.0015;
  trouble = 0;
 
  this->universe = universe;

  PyObject *pyo_universe_spec;

  pyo_universe_spec = PyObject_GetAttrString(universe, "_spec");
  universe_spec = (PyUniverseSpecObject *)pyo_universe_spec;

  PyObject *objectList;
  objectList = PyObject_CallMethod(universe, "objectList", NULL);
  PyObject *object0 = PyList_GetItem(objectList, 0);

  // * Get confarr * //
  PyObject *confobj;
  PyObject *confarr;
  confobj = PyObject_CallMethod(universe, "configuration", NULL);
  confarr = PyObject_GetAttrString(confobj, "array");
  configuration = (PyArrayObject *)confarr;

  vector3 *x;
  x = (vector3 *)configuration->data;

  p_energy_po = new energy_data;

  #if defined(NUMPY)
    gradarr = (PyArrayObject *)PyArray_Copy(configuration);
  #else
    gradarr = (PyArrayObject *)PyArray_FromDims(configuration->nd, configuration->dimensions, PyArray_DOUBLE);
  #endif

  vector3 *f;
  f = (vector3 *)gradarr->data;
  for(int i=0; i<configuration->dimensions[0]; i++){
    f[i][0] = f[i][1] = f[i][2] = .0;
  }

  p_energy_po->gradients = (PyObject *)gradarr;
  p_energy_po->gradient_fn = NULL;
  p_energy_po->force_constants = NULL;
  p_energy_po->fc_fn = NULL;

  int natoms = configuration->dimensions[0];
  int order[natoms+2];
  int acceptance;

  PyObject *prmtop_order_obj = PyObject_GetAttrString(object0, "prmtop_order");
  for(int i=0; i<PyList_Size(prmtop_order_obj); i++){
    order[i] = (int)PyInt_AS_LONG( PyObject_GetAttrString(PyList_GetItem((prmtop_order_obj), i), "number") );
  }
  PyArrayObject *prmtop_order = (PyArrayObject *)prmtop_order_obj;
  order[natoms] = 1;
  order[natoms+1] = 1945;

  acceptance = order[natoms];

  int argc = 6;
  ligdir += '/';
  //gaffdir += '/';
  //string gaff_fn = gaffdir + "gaff.dat";

  /* Options are:
    IC: Internal Coordinates: fully flexible
    TD: Torsional Dynamics: only torsions are flexible 
    RR: Rigid Rings: torsional dynamics with rigid rings
   */
  const char *argv[6] = {
  "-ligdir", ligdir.c_str(),
  "-gaff",  gaff_fn.c_str(),
  "-ictd", "TD"
  };

  //+++++++ Simbody PART ++++++++++++
  bArgParser parser(argc, argv);
  parser.Print();
 
  TARGET_TYPE **indexMap = NULL;
  TARGET_TYPE *PrmToAx_po = NULL;
  TARGET_TYPE *MMTkToPrm_po = NULL;

  std::cout<<"MMTK configuration->dimensions[0]"<<configuration->dimensions[0]<<std::endl<<std::flush;
  indexMap = new TARGET_TYPE*[(configuration->dimensions[0])];
  int _indexMap[natoms][3];
  PrmToAx_po = new TARGET_TYPE[configuration->dimensions[0]];
  MMTkToPrm_po = new TARGET_TYPE[configuration->dimensions[0]];

  int natoms3 = 3*(configuration->dimensions[0]);
  int arrays_cut = 2 + 4*natoms3;

  SHMSZ = (
    2*sizeof(TARGET_TYPE) +       // Counter and flag
    natoms3*sizeof(TARGET_TYPE) + // Positions
//.........这里部分代码省略.........
开发者ID:spirilaurentiu,项目名称:AlGDock,代码行数:101,代码来源:simmain.cpp


示例2: pcap_PcapObject_init

static int
pcap_PcapObject_init(PyObject *p,
                     PyObject *args,
                     PyObject *kwds)
{
  pcap_PcapObject *self     = (pcap_PcapObject *)p;
  static char     *kwlist[] = {"src", "mode", "snaplen", "linktype", NULL};
  char            *mode     = NULL;
  _uint32_t        snaplen  = 65535;
  _uint32_t        linktype = 1;
  PyObject        *pTmp     = NULL;
  PyObject        *pFile;       /* Don't decref, it's borrowed! */

  attempt {
    int tmp;

    tmp = PyArg_ParseTupleAndKeywords(args, kwds, "O|sll", kwlist, &pFile, &mode, &snaplen, &linktype);
    if (! tmp) break;

    if (PyString_Check(pFile)) {
      char *fn;

      fn = PyString_AsString(pFile);
      if (! fn) break;

      if (NULL == mode) {
        mode = "rb";
      }

      pFile = PyFile_FromString(fn, mode);
      if (! pFile) break;

      self->pFile = pFile;
    } else {
      self->pFile = pFile;
      Py_INCREF(self->pFile);
    }

    if ((! mode) || ('r' == mode[0])) {
      /* Try to read in the header. */

      pTmp = PyObject_CallMethod(pFile, "read", "i", sizeof(self->header));
      if (0 == mode) {
        /* If we're in auto-detect mode... */
        if (pTmp) {
          /* And it worked, then we become read-only */
          self->mode = 'r';
        } else {
          /* And it didn't work, then we become write-only */
          PyErr_Clear();
          self->mode = 'w';
        }
      } else {
        self->mode = mode[0];
      }
    } else {
      self->mode = mode[0];
    }

    if ('r' == self->mode) {
      if (! pTmp) break;

      {
        int   tmp;
        char *buf;
        int   len;

        tmp = PyString_AsStringAndSize(pTmp, &buf, &len);
        if (-1 == tmp) {
          break;
        }

        if (len != sizeof(self->header)) {
          PyErr_Format(PyExc_IOError, "Reading header returned wrong number of bytes");
          break;
        }

        memcpy(&(self->header), buf, len);
      }

      if (0xa1b2c3d4 == self->header.magic) {
        self->swap = 0;
      } else if (0xd4c3b2a1 == self->header.magic) {
        self->swap = 1;
      } else {
        PyErr_Format(PyExc_IOError, "Not a pcap file");
        break;
      }
    } else if ('w' == self->mode) {
      /* Write out header */

      memset(&(self->header), 0, sizeof(self->header));
      self->header.magic         = 0xa1b2c3d4;
      self->header.version_major = 2;
      self->header.version_minor = 4;
      self->header.snaplen       = snaplen;
      self->header.linktype      = linktype;
      self->swap                 = 0;

      pTmp = PyObject_CallMethod(pFile, "write", "s#", &(self->header), sizeof(self->header));
//.........这里部分代码省略.........
开发者ID:andyhao567,项目名称:py-pcap,代码行数:101,代码来源:pcap.c


示例3: Py_InitializeEx


//.........这里部分代码省略.........
	_PyImport_FixupExtension("sys", "sys");
	PySys_SetPath(Py_GetPath());
	PyDict_SetItemString(interp->sysdict, "modules",
			     interp->modules);

	_PyImport_Init();

	/* initialize builtin exceptions */
	_PyExc_Init();
	_PyImport_FixupExtension("exceptions", "exceptions");

	/* phase 2 of builtins */
	_PyImport_FixupExtension("__builtin__", "__builtin__");

	_PyImportHooks_Init();

	if (install_sigs)
		initsigs(); /* Signal handling stuff, including initintr() */

#ifdef STACKLESS
	_PyStackless_Init();
#endif
	initmain(); /* Module __main__ */
	if (!Py_NoSiteFlag)
		initsite(); /* Module site */

	/* auto-thread-state API, if available */
#ifdef WITH_THREAD
	_PyGILState_Init(interp, tstate);
#endif /* WITH_THREAD */

	warnings_module = PyImport_ImportModule("warnings");
	if (!warnings_module)
		PyErr_Clear();

#if defined(Py_USING_UNICODE) && defined(HAVE_LANGINFO_H) && defined(CODESET)
	/* On Unix, set the file system encoding according to the
	   user's preference, if the CODESET names a well-known
	   Python codec, and Py_FileSystemDefaultEncoding isn't
	   initialized by other means. Also set the encoding of
	   stdin and stdout if these are terminals.  */

	saved_locale = strdup(setlocale(LC_CTYPE, NULL));
	setlocale(LC_CTYPE, "");
	codeset = nl_langinfo(CODESET);
	if (codeset && *codeset) {
		PyObject *enc = PyCodec_Encoder(codeset);
		if (enc) {
			codeset = strdup(codeset);
			Py_DECREF(enc);
		} else {
			codeset = NULL;
			PyErr_Clear();
		}
	} else
		codeset = NULL;
	setlocale(LC_CTYPE, saved_locale);
	free(saved_locale);

	if (codeset) {
		sys_stream = PySys_GetObject("stdin");
		sys_isatty = PyObject_CallMethod(sys_stream, "isatty", "");
		if (!sys_isatty)
			PyErr_Clear();
		if(sys_isatty && PyObject_IsTrue(sys_isatty) &&
		   PyFile_Check(sys_stream)) {
			if (!PyFile_SetEncoding(sys_stream, codeset))
				Py_FatalError("Cannot set codeset of stdin");
		}
		Py_XDECREF(sys_isatty);

		sys_stream = PySys_GetObject("stdout");
		sys_isatty = PyObject_CallMethod(sys_stream, "isatty", "");
		if (!sys_isatty)
			PyErr_Clear();
		if(sys_isatty && PyObject_IsTrue(sys_isatty) &&
		   PyFile_Check(sys_stream)) {
			if (!PyFile_SetEncoding(sys_stream, codeset))
				Py_FatalError("Cannot set codeset of stdout");
		}
		Py_XDECREF(sys_isatty);

		sys_stream = PySys_GetObject("stderr");
		sys_isatty = PyObject_CallMethod(sys_stream, "isatty", "");
		if (!sys_isatty)
			PyErr_Clear();
		if(sys_isatty && PyObject_IsTrue(sys_isatty) &&
		   PyFile_Check(sys_stream)) {
			if (!PyFile_SetEncoding(sys_stream, codeset))
				Py_FatalError("Cannot set codeset of stderr");
		}
		Py_XDECREF(sys_isatty);

		if (!Py_FileSystemDefaultEncoding)
			Py_FileSystemDefaultEncoding = codeset;
		else
			free(codeset);
	}
#endif
}
开发者ID:Oize,项目名称:pspstacklesspython,代码行数:101,代码来源:pythonrun.c


示例4: modena_model_t_init

static int
modena_model_t_init(modena_model_t *self, PyObject *args, PyObject *kwds)
{
    PyObject *pParameters=NULL, *pModel=NULL;
    char *modelId=NULL;

    static char *kwlist[] = {"model", "modelId", "parameters"};

    if
    (
        !PyArg_ParseTupleAndKeywords
        (
            args, kwds, "|OsO", kwlist, &pModel, &modelId, &pParameters
        )
    )
    {
        return -1;
    }

    if(!pModel)
    {
        PyObject *pName = PyString_FromString("modena.SurrogateModel");
        if(!pName){ Modena_PyErr_Print(); }

        PyObject *pModule = PyImport_Import(pName);
        Py_DECREF(pName);
        if(!pModule){ Modena_PyErr_Print(); }

        PyObject *pDict = PyModule_GetDict(pModule); // Borrowed ref
        if(!pDict){ Modena_PyErr_Print(); }

        pName = PyString_FromString("SurrogateModel");
        if(!pName){ Modena_PyErr_Print(); }

        PyObject *sModel = PyObject_GetItem(pDict, pName);
        Py_DECREF(pName);
        if(!sModel){ Modena_PyErr_Print(); }

        self->pModel = PyObject_CallMethod(sModel, "load", "(z)", modelId);
        Py_DECREF(sModel);
        if(!self->pModel){ Modena_PyErr_Print(); }

        modena_model_get_minMax(self);

        Py_DECREF(pModule);
    }
    else
    {
        Py_INCREF(pModel);
        self->pModel = pModel;

        // Set everything to zero
        self->inputs_minMax_size = 0;
        self->inputs_min = NULL;
        self->inputs_max = NULL;
    }

    //PyObject_Print(self->pModel, stdout, 0);
    //printf("\n");

    PyObject *pOutputs = PyObject_GetAttrString(self->pModel, "outputs");
    if(!pOutputs){ Modena_PyErr_Print(); }
    self->outputs_size = PyDict_Size(pOutputs);
    Py_DECREF(pOutputs);

    PyObject *pMaxArgPos = PyObject_CallMethod
    (
        self->pModel, "inputs_max_argPos", NULL
    );
    if(!pMaxArgPos){ Modena_PyErr_Print(); }
    self->inputs_size = 1 + PyInt_AsSsize_t(pMaxArgPos);
    Py_DECREF(pMaxArgPos);

    self->inherited_inputs_size = 0;

    // Avoiding double indirection in modena_model_call
    // Use modena_function_new to construct, then copy function pointer
    self->mf = modena_function_new(self);
    self->function = self->mf->function;

    self->argPos_used = malloc
    (
        (self->inputs_size + self->inherited_inputs_size)*sizeof(bool)
    );

    modena_model_read_substituteModels(self);

    if(!pParameters)
    {
        pParameters = PyObject_GetAttrString(self->pModel, "parameters");
        if(!pParameters){ Modena_PyErr_Print(); }
    }
    else
    {
        Py_INCREF(pParameters);
    }

    PyObject *pSeq = PySequence_Fast(pParameters, "expected a sequence");
    self->parameters_size = PySequence_Size(pParameters);
    self->parameters = malloc(self->parameters_size*sizeof(double));
//.........这里部分代码省略.........
开发者ID:mandarthombre,项目名称:MoDeNa,代码行数:101,代码来源:modena.c


示例5: generate_mipmap

extern "C" PyObject* generate_mipmap(PyObject*, PyObject* args)
{
    // Convert some of this Python nonsense to good old C
    PyObject* blTexImage = nullptr; // unchecked... better be right
    PyObject* pymm = nullptr;
    if (PyArg_ParseTuple(args, "OO", &blTexImage, &pymm) && blTexImage && pymm) {
        // Since we can't link with PyHSPlasma easily, let's do some roundabout type-checking
        korlib::pyref classindex = PyObject_CallMethod(pymm, "ClassIndex", "");
        static short mipmap_classindex = plFactory::ClassIndex("plMipmap");

        if (PyLong_AsLong(classindex) != mipmap_classindex) {
            PyErr_SetString(PyExc_TypeError, "generate_mipmap expects a Blender ImageTexture and a plMipmap");
            return nullptr;
        }
    } else {
        PyErr_SetString(PyExc_TypeError, "generate_mipmap expects a Blender ImageTexture and a plMipmap");
        return nullptr;
    }

    // Grab the important stuff
    plMipmap* mipmap = ((pyMipmap*)pymm)->fThis;
    korlib::pyref blImage = korlib::getattr<PyObject*>(blTexImage, "image");
    bool makeMipMap = korlib::getattr<bool>(blTexImage, "use_mipmap");
    bool useAlpha = korlib::getattr<bool>(blTexImage, "use_alpha");
    bool calcAlpha = korlib::getattr<bool>(blTexImage, "use_calculate_alpha");

    // Okay, so, here are the assumptions.
    // We assume that the Korman Python code as already created the mipmap's key and named it appropriately
    // So, if we're mipmapping nb01StoneSquareCobble.tga -> nb01StoneSquareCobble.dds as the key name
    // What we now need to do:
    //     1) Make sure this is a POT texture (if not, call scale on the Blender Image)
    //     2) Check calcAlpha and all that rubbish--det DXT1/DXT5/uncompressed
    //     3) "Create" the plMipmap--this allocates internal buffers and such
    //     4) Loop through the levels, going down through the POTs and fill in the pixel data
    // The reason we do this in C instead of python is because it's a lot of iterating over a lot of
    // floating point data (we have to convert to RGB8888, joy). Should be faster here!
    print("Exporting '%s'...", mipmap->getKey()->getName().cstr());

    // Step 1: Resize to POT (if needed) -- don't rely on GLU for this because it may not suppport
    //         NPOT if we're being run on some kind of dinosaur...
    imagesize_t dimensions = get_image_size(blImage);
    size_t width = pow(2., korlib::log2(static_cast<double>(std::get<0>(dimensions))));
    size_t height = pow(2., korlib::log2(static_cast<double>(std::get<1>(dimensions))));
    if (std::get<0>(dimensions) != width || std::get<1>(dimensions) != height) {
        print("\tImage is not a POT (%dx%d)... resizing to %dx%d", std::get<0>(dimensions),
              std::get<1>(dimensions), width, height);
        resize_image(blImage, width, height);
    }

    // Steps 2+3: Translate flags and pass to plMipmap::Create
    // TODO: PNG compression for lossless images
    uint8_t numLevels = (makeMipMap) ? 0 : 1; // 0 means "you figure it out"
    uint8_t compType = (makeMipMap) ? plBitmap::kDirectXCompression : plBitmap::kUncompressed;
    bool alphaChannel = useAlpha || calcAlpha;
    mipmap->Create(width, height, numLevels, compType, plBitmap::kRGB8888, alphaChannel ? plBitmap::kDXT5 : plBitmap::kDXT1);

    // Step 3.9: Load the image into OpenGL
    gl_loadimage guard(blImage);
    if (!guard.success()) {
        PyErr_SetString(PyExc_RuntimeError, "failed to load image into OpenGL");
        return nullptr;
    }

    // Step 4: Now it's a matter of looping through all the levels and exporting the image
    for (size_t i = 0; i < mipmap->getNumLevels(); ++i) {
        stuff_mip_level(mipmap, i, blImage, calcAlpha);
    }

    Py_RETURN_NONE;
}
开发者ID:Lunanne,项目名称:korman,代码行数:70,代码来源:generate_mipmap.cpp


示例6: image_new

static PyObject* image_new( PyObject* self, PyObject* args )
{
    ImageObject* imageobj = NULL;
    PyObject* pilobj = NULL;
    PyObject* modestrobj = NULL;
    PyObject* sizeobj = NULL;
    PyObject* datastrobj = NULL;
    unsigned char* data;
    char* modestr;
    int i;
    int pixelsize;
    static PyObject* PILmodule = NULL;
    PyObject* oldpilobj;
    PyObject* nameobj;

    if ( !PyArg_ParseTuple( args, "O:new_image", &pilobj ) )
	return NULL;
    Py_INCREF( pilobj );

    if ( PyString_Check( pilobj ) )
    {
	// object is a string; assume it's a filename and attempt to create the PIL object ourselves;
#if 0
	printf( "fine, creating the PIL object myself\n" );
#endif

	if ( PILmodule == NULL )
	{
	    PyObject* name = PyString_FromString( "Image" );
	    PILmodule = PyImport_Import( name );
	    Py_DECREF( name );
	    if ( PILmodule == NULL )
	    {
		PyErr_SetString( ImageError, "failed to find PIL module" );
		goto error;
	    }
	}

	nameobj = pilobj;
	
	oldpilobj = pilobj;
	pilobj = PyObject_CallMethod( PILmodule, "open", "O", pilobj );
	Py_DECREF( oldpilobj );
	if ( pilobj == NULL )
	    goto error;
	Py_INCREF( pilobj );
    }
    else
	nameobj = Py_None;
    
    imageobj = PyObject_New( ImageObject, &ImageType );

    Py_INCREF( nameobj );
    imageobj->filename = nameobj;

    modestrobj = PyObject_GetAttrString( pilobj, "mode" );
    modestr = PyString_AsString( modestrobj );
    if ( strcmp( modestr, "RGBA" ) == 0 )
    {
	pixelsize = 4;
    }
    else if ( strcmp( modestr, "RGB" ) == 0 )
    {
	pixelsize = 3;
    }
    else
    {
#if 0
	printf( "attempting conversion to RGB\n" );
#endif
	
	// need to convert image to RGB
	oldpilobj = pilobj;
	pilobj = PyObject_CallMethod( pilobj, "convert", "s", "RGB" );
	Py_DECREF( oldpilobj );
	if ( pilobj == NULL )
	    goto error;
	Py_INCREF( pilobj );

	pixelsize = 3;
    }

    sizeobj = PyObject_GetAttrString( pilobj, "size" );
    if ( !PyTuple_Check( sizeobj ) || PyTuple_Size( sizeobj ) != 2 )
    {
	PyErr_SetString( ImageError, "size attribute is wrong wrong wrong" );
	Py_DECREF( sizeobj );
	Py_DECREF( pilobj );
	return NULL;
    }

    imageobj->w = PyInt_AsLong( PyTuple_GetItem( sizeobj, 0 ) );
    imageobj->h = PyInt_AsLong( PyTuple_GetItem( sizeobj, 1 ) );
    if ( imageobj->w < 1 || imageobj->h < 1 )
    {
	PyErr_Format( ImageError, "PIL says image size is %d x %d; that can't be right",
		      imageobj->w, imageobj->h );
	goto error;
    }
#if 0
//.........这里部分代码省略.........
开发者ID:gcross,项目名称:QC-Talks,代码行数:101,代码来源:diaimage.c


示例7: subprocess_fork_exec

static PyObject *
subprocess_fork_exec(PyObject* self, PyObject *args)
{
    PyObject *gc_module = NULL;
    PyObject *executable_list, *py_close_fds, *py_fds_to_keep;
    PyObject *env_list, *preexec_fn;
    PyObject *process_args, *converted_args = NULL, *fast_args = NULL;
    PyObject *preexec_fn_args_tuple = NULL;
    int p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite;
    int errpipe_read, errpipe_write, close_fds, restore_signals;
    int call_setsid;
    PyObject *cwd_obj, *cwd_obj2;
    const char *cwd;
    pid_t pid;
    int need_to_reenable_gc = 0;
    char *const *exec_array, *const *argv = NULL, *const *envp = NULL;
    Py_ssize_t arg_num, num_fds_to_keep;

    if (!PyArg_ParseTuple(
            args, "OOOOOOiiiiiiiiiiO:fork_exec",
            &process_args, &executable_list, &py_close_fds, &py_fds_to_keep,
            &cwd_obj, &env_list,
            &p2cread, &p2cwrite, &c2pread, &c2pwrite,
            &errread, &errwrite, &errpipe_read, &errpipe_write,
            &restore_signals, &call_setsid, &preexec_fn))
        return NULL;

    close_fds = PyObject_IsTrue(py_close_fds);
    if (close_fds && errpipe_write < 3) {  /* precondition */
        PyErr_SetString(PyExc_ValueError, "errpipe_write must be >= 3");
        return NULL;
    }
    num_fds_to_keep = PySequence_Length(py_fds_to_keep);
    if (num_fds_to_keep < 0) {
        PyErr_SetString(PyExc_ValueError, "bad fds_to_keep");
        return NULL;
    }

    /* We need to call gc.disable() when we'll be calling preexec_fn */
    if (preexec_fn != Py_None) {
        PyObject *result;
        gc_module = PyImport_ImportModule("gc");
        if (gc_module == NULL)
            return NULL;
        result = PyObject_CallMethod(gc_module, "isenabled", NULL);
        if (result == NULL) {
            Py_DECREF(gc_module);
            return NULL;
        }
        need_to_reenable_gc = PyObject_IsTrue(result);
        Py_DECREF(result);
        if (need_to_reenable_gc == -1) {
            Py_DECREF(gc_module);
            return NULL;
        }
        result = PyObject_CallMethod(gc_module, "disable", NULL);
        if (result == NULL) {
            Py_DECREF(gc_module);
            return NULL;
        }
        Py_DECREF(result);
    }

    exec_array = _PySequence_BytesToCharpArray(executable_list);
    if (!exec_array)
        return NULL;

    /* Convert args and env into appropriate arguments for exec() */
    /* These conversions are done in the parent process to avoid allocating
       or freeing memory in the child process. */
    if (process_args != Py_None) {
        Py_ssize_t num_args;
        /* Equivalent to:  */
        /*  tuple(PyUnicode_FSConverter(arg) for arg in process_args)  */
        fast_args = PySequence_Fast(process_args, "argv must be a tuple");
        num_args = PySequence_Fast_GET_SIZE(fast_args);
        converted_args = PyTuple_New(num_args);
        if (converted_args == NULL)
            goto cleanup;
        for (arg_num = 0; arg_num < num_args; ++arg_num) {
            PyObject *borrowed_arg, *converted_arg;
            borrowed_arg = PySequence_Fast_GET_ITEM(fast_args, arg_num);
            if (PyUnicode_FSConverter(borrowed_arg, &converted_arg) == 0)
                goto cleanup;
            PyTuple_SET_ITEM(converted_args, arg_num, converted_arg);
        }

        argv = _PySequence_BytesToCharpArray(converted_args);
        Py_CLEAR(converted_args);
        Py_CLEAR(fast_args);
        if (!argv)
            goto cleanup;
    }

    if (env_list != Py_None) {
        envp = _PySequence_BytesToCharpArray(env_list);
        if (!envp)
            goto cleanup;
    }

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


示例8: start_watcher

void start_watcher(int i, struct uwsgi_socket* uwsgi_sock) {
        PyObject_CallMethod(ugevent.watchers[i], "start", "Oli", uwsgi_gevent_main,(long)uwsgi_sock, i);
}
开发者ID:RyuaNerin,项目名称:uwsgi,代码行数:3,代码来源:gevent.c


示例9: Reference_get_object

PyObject *
Reference_get_object(Reference *self)
{
    return PyObject_CallMethod((PyObject *) self, "peel", NULL);
}
开发者ID:KINFOO,项目名称:pygit2,代码行数:5,代码来源:reference.c


示例10: PyObject_CallMethod

void SlowScan::playFile(PyObject* file_path)
{
	
	// Call the function "PrintText" in PythonLand.
    pValue = PyObject_CallMethod(pInstance, "playFile", "(O)", file_path);
}
开发者ID:uccubecats,项目名称:MaineCoon,代码行数:6,代码来源:slowscan.cpp


示例11: _descriptor_from_pep3118_format

NPY_NO_EXPORT PyArray_Descr*
_descriptor_from_pep3118_format(char *s)
{
    char *buf, *p;
    int in_name = 0;
    int obtained;
    PyObject *descr;
    PyObject *str;
    PyObject *_numpy_internal;

    if (s == NULL) {
        return PyArray_DescrNewFromType(NPY_BYTE);
    }

    /* Fast path */
    obtained = _descriptor_from_pep3118_format_fast(s, &descr);
    if (obtained) {
        return (PyArray_Descr*)descr;
    }

    /* Strip whitespace, except from field names */
    buf = malloc(strlen(s) + 1);
    if (buf == NULL) {
        return NULL;
    }
    p = buf;
    while (*s != '\0') {
        if (*s == ':') {
            in_name = !in_name;
            *p = *s;
            p++;
        }
        else if (in_name || !NumPyOS_ascii_isspace(*s)) {
            *p = *s;
            p++;
        }
        s++;
    }
    *p = '\0';

    str = PyUString_FromStringAndSize(buf, strlen(buf));
    if (str == NULL) {
        free(buf);
        return NULL;
    }

    /* Convert */
    _numpy_internal = PyImport_ImportModule("numpy.core._internal");
    if (_numpy_internal == NULL) {
        Py_DECREF(str);
        free(buf);
        return NULL;
    }
    descr = PyObject_CallMethod(
        _numpy_internal, "_dtype_from_pep3118", "O", str);
    Py_DECREF(str);
    Py_DECREF(_numpy_internal);
    if (descr == NULL) {
        PyErr_Format(PyExc_ValueError,
                     "'%s' is not a valid PEP 3118 buffer format string", buf);
        free(buf);
        return NULL;
    }
    if (!PyArray_DescrCheck(descr)) {
        PyErr_Format(PyExc_RuntimeError,
                     "internal error: numpy.core._internal._dtype_from_pep3118 "
                     "did not return a valid dtype, got %s", buf);
        Py_DECREF(descr);
        free(buf);
        return NULL;
    }
    free(buf);
    return (PyArray_Descr*)descr;
}
开发者ID:Benj1,项目名称:numpy,代码行数:74,代码来源:buffer.c


示例12: while


//.........这里部分代码省略.........
            PyObject *throw_method = PyObject_GetAttr( value, const_str_plain_throw );

            if ( throw_method )
            {
                retval = PyObject_CallFunctionObjArgs( throw_method, generator->m_exception_type, generator->m_exception_value, generator->m_exception_tb, NULL );
                Py_DECREF( throw_method );

                if (unlikely( send_value == NULL ))
                {
                    if ( EXCEPTION_MATCH_BOOL_SINGLE( GET_ERROR_OCCURRED(), PyExc_StopIteration ) )
                    {
                        return ERROR_GET_STOP_ITERATION_VALUE();
                    }

                    return NULL;
                }

                generator->m_exception_type = NULL;
                generator->m_exception_value = NULL;
                generator->m_exception_tb = NULL;
            }
            else if ( EXCEPTION_MATCH_BOOL_SINGLE( GET_ERROR_OCCURRED(), PyExc_AttributeError ) )
            {
                CLEAR_ERROR_OCCURRED();

                RAISE_GENERATOR_EXCEPTION( generator );

                return NULL;
            }
            else
            {
                assert( ERROR_OCCURRED() );

                Py_CLEAR( generator->m_exception_type );
                Py_CLEAR( generator->m_exception_value );
                Py_CLEAR( generator->m_exception_tb );

                return NULL;
            }

        }
        else if ( PyGen_CheckExact( value ) )
        {
            retval = PyGen_Send( (PyGenObject *)value, Py_None );
        }
        else if ( send_value == Py_None && Py_TYPE( value )->tp_iternext != NULL )
        {
            retval = Py_TYPE( value )->tp_iternext( value );
        }
        else
        {
            // Bug compatibility here, before 3.3 tuples were unrolled in calls, which is what
            // PyObject_CallMethod does.
#if PYTHON_VERSION >= 340
            retval = PyObject_CallMethodObjArgs( value, const_str_plain_send, send_value, NULL );
#else
            retval = PyObject_CallMethod( value, (char *)"send", (char *)"O", send_value );
#endif
        }

        // Check the sub-generator result
        if ( retval == NULL )
        {
            PyObject *error = GET_ERROR_OCCURRED();
            if ( error == NULL )
            {
                return INCREASE_REFCOUNT( Py_None ) ;
            }

            // The sub-generator has given an exception. In case of
            // StopIteration, we need to check the value, as it is going to be
            // the expression value of this "yield from", and we are done. All
            // other errors, we need to raise.
            if (likely( EXCEPTION_MATCH_BOOL_SINGLE( error, PyExc_StopIteration ) ))
            {
                return ERROR_GET_STOP_ITERATION_VALUE();
            }

            return NULL;
        }
        else
        {
            generator->m_yielded = retval;

#if PYTHON_VERSION >= 350
            generator->m_yieldfrom = value;
#endif
            // Return to the calling context.
            swapFiber( &generator->m_yielder_context, &generator->m_caller_context );

#if PYTHON_VERSION >= 350
            generator->m_yieldfrom = NULL;
#endif

            send_value = generator->m_yielded;

            CHECK_OBJECT( send_value );
        }
    }
}
开发者ID:fluxer,项目名称:spm,代码行数:101,代码来源:CompiledGeneratorType.c


示例13: PyObject_CallMethod

		PyObject *ret = PyObject_CallMethod(watcher, "start", "OO", current, watcher);
        	if (!ret) {
                	stop_the_watchers_and_clear
                	return -1;
        	}
        	Py_DECREF(ret);

        	ret = PyObject_CallMethod(timer, "start", "OO", current, timer);
        	if (!ret) {
                	stop_the_watchers_and_clear
                	return -1;
        	}
        	Py_DECREF(ret);

        	ret = PyObject_CallMethod(ugevent.hub, "switch", NULL);
		wsgi_req->switches++;
        	if (!ret) {
                	stop_the_watchers_and_clear
                	return -1;
        	}
        	Py_DECREF(ret);

        	if (ret == timer) {
                	stop_the_watchers_and_clear
                	return 0;
        	}

		UWSGI_RELEASE_GIL;	
                ssize_t rlen = read(wsgi_req->poll.fd, tmp_buf+*tmp_pos, remains);
                if (rlen <= 0) {
开发者ID:chiwong,项目名称:flask_quickstart,代码行数:30,代码来源:gevent.c


示例14: PyObject_CallMethod

//-------------------------------------------------------------------------------------
PyObject* Map::__py_get(PyObject* self, PyObject* args)
{
	return PyObject_CallMethod(static_cast<Map*>(self)->pyDict_, 
		const_cast<char*>("get"), const_cast<char*>("O"), args);
}
开发者ID:lweijin,项目名称:kbengine,代码行数:6,代码来源:map.cpp


示例15: xid_recover

PyObject *
xid_recover(PyObject *conn)
{
    PyObject *rv = NULL;
    PyObject *curs = NULL;
    PyObject *xids = NULL;
    xidObject *xid = NULL;
    PyObject *recs = NULL;
    PyObject *rec = NULL;
    PyObject *item = NULL;
    PyObject *tmp;
    Py_ssize_t len, i;

    /* curs = conn.cursor()
     * (sort of. Use the real cursor in case the connection returns
     * somenthing non-dbapi -- see ticket #114) */
    if (!(curs = PyObject_CallFunctionObjArgs(
        (PyObject *)&cursorType, conn, NULL))) { goto exit; }

    /* curs.execute(...) */
    if (!(tmp = PyObject_CallMethod(curs, "execute", "s",
        "SELECT gid, prepared, owner, database FROM pg_prepared_xacts")))
    {
        goto exit;
    }
    Py_DECREF(tmp);

    /* recs = curs.fetchall() */
    if (!(recs = PyObject_CallMethod(curs, "fetchall", NULL))) { goto exit; }

    /* curs.close() */
    if (!(tmp = PyObject_CallMethod(curs, "close", NULL))) { goto exit; }
    Py_DECREF(tmp);

    /* Build the list with return values. */
    if (0 > (len = PySequence_Size(recs))) { goto exit; }
    if (!(xids = PyList_New(len))) { goto exit; }

    /* populate the xids list */
    for (i = 0; i < len; ++i) {
        if (!(rec = PySequence_GetItem(recs, i))) { goto exit; }

        /* Get the xid with the XA triple set */
        if (!(item = PySequence_GetItem(rec, 0))) { goto exit; }
        if (!(xid = xid_from_string(item))) { goto exit; }
        Py_CLEAR(item);

        /* set xid.prepared */
        Py_CLEAR(xid->prepared);
        if (!(xid->prepared = PySequence_GetItem(rec, 1))) { goto exit; }

        /* set xid.owner */
        Py_CLEAR(xid->owner);
        if (!(xid->owner = PySequence_GetItem(rec, 2))) { goto exit; }

        /* set xid.database */
        Py_CLEAR(xid->database);
        if (!(xid->database = PySequence_GetItem(rec, 3))) { goto exit; }

        /* xid finished: add it to the returned list */
        PyList_SET_ITEM(xids, i, (PyObject *)xid);
        xid = NULL;  /* ref stolen */

        Py_CLEAR(rec);
    }

    /* set the return value. */
    rv = xids;
    xids = NULL;

exit:
    Py_XDECREF(xids);
    Py_XDECREF(xid);
    Py_XDECREF(curs);
    Py_XDECREF(recs);
    Py_XDECREF(rec);
    Py_XDECREF(item);

    return rv;
}
开发者ID:psycopg,项目名称:psycopg2,代码行数:80,代码来源:xid_type.c


示例16: convert_pydatetime_to_datetimestruct


//.........这里部分代码省略.........
    Py_DECREF(tmp);

    /* Get the minute */
    tmp = PyObject_GetAttrString(obj, "minute");
    if (tmp == NULL) {
        return -1;
    }
    out->min = PyInt_AsLong(tmp);
    if (out->min == -1 && PyErr_Occurred()) {
        Py_DECREF(tmp);
        return -1;
    }
    Py_DECREF(tmp);

    /* Get the second */
    tmp = PyObject_GetAttrString(obj, "second");
    if (tmp == NULL) {
        return -1;
    }
    out->sec = PyInt_AsLong(tmp);
    if (out->sec == -1 && PyErr_Occurred()) {
        Py_DECREF(tmp);
        return -1;
    }
    Py_DECREF(tmp);

    /* Get the microsecond */
    tmp = PyObject_GetAttrString(obj, "microsecond");
    if (tmp == NULL) {
        return -1;
    }
    out->us = PyInt_AsLong(tmp);
    if (out->us == -1 && PyErr_Occurred()) {
        Py_DECREF(tmp);
        return -1;
    }
    Py_DECREF(tmp);

    if (out->hour < 0 || out->hour >= 24 || out->min < 0 || out->min >= 60 ||
        out->sec < 0 || out->sec >= 60 || out->us < 0 || out->us >= 1000000) {
        goto invalid_time;
    }

    /* Apply the time zone offset if it exists */
    if (PyObject_HasAttrString(obj, "tzinfo")) {
        tmp = PyObject_GetAttrString(obj, "tzinfo");
        if (tmp == NULL) {
            return -1;
        }
        if (tmp == Py_None) {
            Py_DECREF(tmp);
        } else {
            PyObject *offset;
            int seconds_offset, minutes_offset;

            /* The utcoffset function should return a timedelta */
            offset = PyObject_CallMethod(tmp, "utcoffset", "O", obj);
            if (offset == NULL) {
                Py_DECREF(tmp);
                return -1;
            }
            Py_DECREF(tmp);

            /*
             * The timedelta should have a function "total_seconds"
             * which contains the value we want.
             */
            tmp = PyObject_CallMethod(offset, "total_seconds", "");
            if (tmp == NULL) {
                return -1;
            }
            seconds_offset = PyInt_AsLong(tmp);
            if (seconds_offset == -1 && PyErr_Occurred()) {
                Py_DECREF(tmp);
                return -1;
            }
            Py_DECREF(tmp);

            /* Convert to a minutes offset and apply it */
            minutes_offset = seconds_offset / 60;

            add_minutes_to_datetimestruct(out, -minutes_offset);
        }
    }

    return 0;

invalid_date:
    PyErr_Format(PyExc_ValueError,
                 "Invalid date (%d,%d,%d) when converting to NumPy datetime",
                 (int)out->year, (int)out->month, (int)out->day);
    return -1;

invalid_time:
    PyErr_Format(PyExc_ValueError,
                 "Invalid time (%d,%d,%d,%d) when converting "
                 "to NumPy datetime",
                 (int)out->hour, (int)out->min, (int)out->sec, (int)out->us);
    return -1;
}
开发者ID:BobMcFry,项目名称:pandas,代码行数:101,代码来源:np_datetime.c


示例17: main

int main(void)
{
	Py_Initialize();
	if(!Py_IsInitialized())
		return -1;
	
	PyRun_SimpleString("import sys");
	//where you put your py file
	PyRun_SimpleString("sys.path.append('../')");
	//Import 
	PyObject* pModule = PyImport_ImportModule("pc");//no *.py
	if(!pModule)
	{
		printf("can't open python file!\n");
		return -1;
	}
	//Dict module
	PyObject* pDict = PyModule_GetDict(pModule);
	if(!pDict)
	{
		printf("can't find dictionary.\n");
		return -1;
	}
	printDict(pDict);

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

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

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

	return 0;
}
开发者ID:no7dw,项目名称:c-python,代码行数:76,代码来源:t2.cpp


示例18: PyArray_DTypeFromObjectHelper


//.........这里部分代码省略.........
        if (NpyCapsule_Check(ip)) {
            inter = (PyArrayInterface *)NpyCapsule_AsVoidPtr(ip);
            if (inter->two == 2) {
                PyOS_snprintf(buf, sizeof(buf),
                        "|%c%d", inter->typekind, inter->itemsize);
                dtype = _array_typedescr_fromstr(buf);
                Py_DECREF(ip);
                if (dtype == NULL) {
                    goto fail;
                }
                goto promote_types;
            }
        }
        Py_DECREF(ip);
    }

    /* The old buffer interface */
#if !defined(NPY_PY3K)
    if (PyBuffer_Check(obj)) {
        dtype = PyArray_DescrNewFromType(NPY_VOID);
        if (dtype == NULL) {
            goto fail;
        }
        dtype->elsize = Py_TYPE(obj)->tp_as_sequence->sq_length(obj);
        PyErr_Clear();
        goto promote_types;
    }
#endif

    /* The __array__ attribute */
    ip = PyArray_GetAttrString_SuppressException(obj, "__array__");
    if (ip != NULL) {
        Py_DECREF(ip);
        ip = PyObject_CallMethod(obj, "__array__", NULL);
        if(ip && PyArray_Check(ip)) {
            dtype = PyArray_DESCR((PyArrayObject *)ip);
            Py_INCREF(dtype);
            Py_DECREF(ip);
            goto promote_types;
        }
        Py_XDECREF(ip);
        if (PyErr_Occurred()) {
            goto fail;
        }
    }

    /* Not exactly sure what this is about... */
#if !defined(NPY_PY3K)
    if (PyInstance_Check(obj)) {
        dtype = _use_default_type(obj);
        if (dtype == NULL) {
            goto fail;
        }
        else {
            goto promote_types;
        }
    }
#endif

    /*
     * If we reached the maximum recursion depth without hitting one
     * of the above cases, the output dtype should be OBJECT
 

鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
C++ PyObject_CallMethodObjArgs函数代码示例发布时间:2022-05-30
下一篇:
C++ PyObject_CallFunctionObjArgs函数代码示例发布时间: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