Ejemplo n.º 1
0
void CallPythonCallback(PyObject* callable, const char* format, ...)
{
    va_list vargs;
    va_start(vargs, format);
    PyObject* arglist = Py_VaBuildValue(format, vargs);
    va_end(vargs);

    if (arglist)
    {
        PyObject* result = PyObject_CallObject(callable, arglist);
        Py_DECREF(arglist);
        if (result)
        {
            Py_DECREF(result);
        }
        else
        {
            PyErr_Print();
        }
    }
    else
    {
        PyErr_Print();
    }
}
Ejemplo n.º 2
0
int
PP_Run_Method(PyObject *pobject,  const char *method,
                  const char *resfmt,   void *cresult,        /* convert to c/c++ */
                  const char *argfmt,   ... /* arg,... */ )   /* convert to python */
{
    PyObject *pmeth, *pargs, *presult;
    va_list argslist;                              /* "pobject.method(args)" */
    va_start(argslist, argfmt);

    Py_Initialize();                               /* init if first time */
    pmeth = PyObject_GetAttrString(pobject, method);  
    if (pmeth == NULL)                             /* get callable object */
        return -1;                                 /* bound method? has self */
	/* handle zero args different */
//	if(resfmt == 0 || strcmp(resfmt,"") == 0)
//		pargs = Py_BuildValue("()");
//	else
		pargs = Py_VaBuildValue(argfmt, argslist);     /* args: c->python */

    if (pargs == NULL) {
        Py_DECREF(pmeth);
        return -1;
    }
    if (PP_DEBUG)                                    /* debug it too? */ 
        presult = PP_Debug_Function(pmeth, pargs); 
    else 
        presult = PyEval_CallObject(pmeth, pargs);   /* run interpreter */

    Py_DECREF(pmeth);
    Py_DECREF(pargs);
//	if(cresult != 0 && resfmt != 0)
		return PP_Convert_Result(presult, resfmt, cresult);    /* to C format */
//	else 
//		return 0;
}
Ejemplo n.º 3
0
int
PP_Run_Function(const char *modname, const char *funcname,          /* load from module */
                const char *resfmt,  void *cresult,           /* convert to c/c++ */
                const char *argfmt,  ... /* arg, arg... */ )  /* convert to python */
{
    /* call a function or class in a module */
    PyObject *func, *args, *presult;
    va_list argslist;
    va_start(argslist, argfmt);                   /* "modname.funcname(args)" */

    func = PP_Load_Attribute(modname, funcname);  /* may reload; incref'd */
    if (func == NULL)                             /* func or class or C type */
        return -1;
    args = Py_VaBuildValue(argfmt, argslist);     /* convert args to python */
    if (args == NULL) {                           /* args incref'd */
        Py_DECREF(func);
        return -1;
    }
    if (PP_DEBUG && strcmp(modname, "pdb") != 0)    /* debug this call? */
        presult = PP_Debug_Function(func, args);    /* run in pdb; incref'd */
    else
        presult = PyEval_CallObject(func, args);    /* run function; incref'd */

    Py_DECREF(func);
    Py_DECREF(args);                                    /* result may be None */
    return PP_Convert_Result(presult, resfmt, cresult); /* convert result to C*/
}
Ejemplo n.º 4
0
static nsresult do_dispatch(
	PyObject *pPyObject,
	PyObject **ppResult,
	const char *szMethodName,
	const char *szFormat,
	va_list va
	)
{
	NS_PRECONDITION(ppResult, "Must provide a result buffer");
	*ppResult = nsnull;
	// Build the Invoke arguments...
	PyObject *args = NULL;
	PyObject *method = NULL;
	PyObject *real_ob = NULL;
	nsresult ret = NS_ERROR_FAILURE;
	if ( szFormat )
		args = Py_VaBuildValue((char *)szFormat, va);
	else
		args = PyTuple_New(0);
	if ( !args )
		goto done;

	// make sure a tuple.
	if ( !PyTuple_Check(args) ) {
		PyObject *a = PyTuple_New(1);
		if ( a == NULL )
		{
			Py_DECREF(args);
			goto done;
		}
		PyTuple_SET_ITEM(a, 0, args);
		args = a;
	}
	// Bit to a hack here to maintain the use of a policy.
	// We actually get the policies underlying object
	// to make the call on.
	real_ob = PyObject_GetAttrString(pPyObject, "_obj_");
	if (real_ob == NULL) {
		PyErr_Format(PyExc_AttributeError, "The policy object does not have an '_obj_' attribute.");
		goto done;
	}
	method = PyObject_GetAttrString(real_ob, (char *)szMethodName);
	if ( !method ) {
		PyErr_Clear();
		ret = NS_PYXPCOM_NO_SUCH_METHOD;
		goto done;
	}
	// Make the call
	*ppResult = PyEval_CallObject(method, args);
	ret = *ppResult ? NS_OK : NS_ERROR_FAILURE;
done:
	Py_XDECREF(method);
	Py_XDECREF(real_ob);
	Py_XDECREF(args);
	return ret;
}
Ejemplo n.º 5
0
PyObject *
PyObject_CallMethod(PyObject *o, char *name, char *format, ...)
{
	va_list va;
	PyObject *args, *func = 0, *retval;
	va_start(va, format);

	if (o == NULL || name == NULL) {
		va_end(va);
		return null_error();
	}

	func = PyObject_GetAttrString(o, name);
	if (func == NULL) {
		va_end(va);
		PyErr_SetString(PyExc_AttributeError, name);
		return 0;
	}

	if (!PyCallable_Check(func)) {
		va_end(va);
		return type_error("call of non-callable attribute");
	}

	if (format && *format)
		args = Py_VaBuildValue(format, va);
	else
		args = PyTuple_New(0);

	va_end(va);

	if (!args)
		return NULL;

	if (!PyTuple_Check(args)) {
		PyObject *a;

		a = PyTuple_New(1);
		if (a == NULL)
			return NULL;
		if (PyTuple_SetItem(a, 0, args) < 0)
			return NULL;
		args = a;
	}

	retval = PyObject_CallObject(func, args);

	Py_DECREF(args);
	Py_DECREF(func);

	return retval;
}
Ejemplo n.º 6
0
int
PP_Set_Member(PyObject *pobject, const char *attrname,
                  const char *argfmt,  ... /* arg,... */ )    /* convert to python */
{
    int result;
    PyObject *pval;
    va_list argslist;                             /* "pobject.attrname = v" */
    va_start(argslist, argfmt);
    Py_Initialize();                              /* init if first time */
    pval = Py_VaBuildValue(argfmt, argslist);     /* input: C->Python */
    if (pval == NULL) 
        return -1;
    result = PyObject_SetAttrString(pobject, attrname, pval);     /* setattr */
    Py_DECREF(pval); 
    return result;
}
Ejemplo n.º 7
0
int
PP_Set_Global(const char *modname, const char *varname, const char *valfmt, ... /* cval(s) */) 
{
    int result;
    PyObject *module, *val;                     /* "modname.varname = val" */
    va_list cvals;
    va_start(cvals, valfmt);                    /* C args after valfmt */

    module = PP_Load_Module(modname);           /* get/load module */
    if (module == NULL) 
        return -1;
    val = Py_VaBuildValue(valfmt, cvals);       /* convert input to Python */
    va_end(cvals);
    if (val == NULL) 
        return -1;
    result = PyObject_SetAttrString(module, varname, val); 
    Py_DECREF(val);                             /* set global module var */
    return result;                              /* decref val: var owns it */
}                                               /* 0=success, varname set */
Ejemplo n.º 8
0
int
PP_Run_Known_Callable(PyObject *object,               /* func|class|method */
                      const char *resfmt, void *cresult,    /* skip module fetch */
                      const char *argfmt, ... /* arg,.. */) /* convert args, result */
{
    /* call a known callable object */
    PyObject *args, *presult;
    va_list argslist;
    va_start(argslist, argfmt);                     /* "return object(args)" */

    Py_Initialize(); 
    args = Py_VaBuildValue(argfmt, argslist);       /* convert args to python */
    if (args == NULL)                               /* args incref'd */
        return -1;
    if (PP_DEBUG)                                   /* debug this call? */
        presult = PP_Debug_Function(object, args);  /* run in pdb; incref'd */
    else
        presult = PyEval_CallObject(object, args);  /* run function; incref'd */

    Py_DECREF(args);                                    /* result may be None */
    return PP_Convert_Result(presult, resfmt, cresult); /* convert result to C*/
}
Ejemplo n.º 9
0
PyObject *
PyObject_CallFunction(PyObject *callable, char *format, ...)
{
	va_list va;
	PyObject *args, *retval;
	va_start(va, format);

	if (callable == NULL) {
		va_end(va);
		return null_error();
	}

	if (format)
		args = Py_VaBuildValue(format, va);
	else
		args = PyTuple_New(0);

	va_end(va);
	
	if (args == NULL)
		return NULL;

	if (!PyTuple_Check(args)) {
		PyObject *a;

		a = PyTuple_New(1);
		if (a == NULL)
			return NULL;
		if (PyTuple_SetItem(a, 0, args) < 0)
			return NULL;
		args = a;
	}
	retval = PyObject_CallObject(callable, args);

	Py_DECREF(args);

	return retval;
}
Ejemplo n.º 10
0
/* Add a dummy frame to the traceback so the developer has a better idea of what C code was doing 

   @param filename: Use __FILE__ for this - it will be the filename reported in the frame
   @param lineno: Use __LINE__ for this - it will be the line number reported in the frame
   @param functionname: Name of the function reported
   @param localsformat: Format string for Py_BuildValue( that must specify a dictionary or NULL to make
                        an empty dictionary.  An example is "{s:i, s: s}" with the varargs then conforming
			to this format (the corresponding params could be "seven", 7, "foo", "bar"

*/
static void AddTraceBackHere(const char *filename, int lineno, const char *functionname, const char *localsformat, ...)
{
  PyObject *srcfile=0, *funcname=0, *empty_dict=0, *empty_tuple=0, *empty_string=0, *localargs=0, *empty_code=0;
  PyCodeObject *code=0;
  PyFrameObject *frame=0;
  va_list localargsva;

  va_start(localargsva, localsformat);

  assert(PyErr_Occurred());

#if PY_VERSION_HEX<0x03000000
  srcfile=PyString_FromString(filename);
  funcname=PyString_FromString(functionname);
#else
  srcfile=PyUnicode_FromString(filename);
  funcname=PyUnicode_FromString(functionname);
#endif
  empty_dict=PyDict_New();
  empty_tuple=PyTuple_New(0);
#if PY_VERSION_HEX<0x03000000
  empty_string=PyString_FromString("");
  empty_code=PyString_FromString("");
#else
  empty_string=PyUnicode_FromString("");
  empty_code=PyBytes_FromStringAndSize(NULL,0);
#endif

  localargs=localsformat?(Py_VaBuildValue((char *)localsformat, localargsva)):PyDict_New();
  if(localsformat)
    assert(localsformat[0]=='{');
  if(localargs)
    assert(PyDict_Check(localargs));

  /* did any fail? */
  if (!srcfile || !funcname || !empty_dict || !empty_tuple || !empty_string)
    goto end;

  /* make the dummy code object */
  code = PyCode_New(
     0,            /*int argcount,*/
#if PY_VERSION_HEX >= 0x03000000
     0,            /*int kwonlyargcount*/
#endif
     0,            /*int nlocals,*/
     0,            /*int stacksize,*/
     0,            /*int flags,*/
     empty_code,   /*PyObject *code,*/
     empty_tuple,  /*PyObject *consts,*/
     empty_tuple,  /*PyObject *names,*/
     empty_tuple,  /*PyObject *varnames,*/
     empty_tuple,  /*PyObject *freevars,*/
     empty_tuple,  /*PyObject *cellvars,*/
     srcfile,      /*PyObject *filename,*/
     funcname,     /*PyObject *name,*/
     lineno,       /*int firstlineno,*/
     empty_code    /*PyObject *lnotab*/
   );
  if (!code) goto end;

  /* make the dummy frame */
  frame=PyFrame_New(
           PyThreadState_Get(), /*PyThreadState *tstate,*/
	   code,                /*PyCodeObject *code,*/
	   empty_dict,          /*PyObject *globals,*/
	   localargs            /*PyObject *locals*/
	   );
  if(!frame) goto end;

  /* add dummy frame to traceback */
  frame->f_lineno=lineno;
  PyTraceBack_Here(frame);
  
  /* this epilogue deals with success or failure cases */
 end:
  va_end(localargsva);
  Py_XDECREF(localargs);
  Py_XDECREF(srcfile);
  Py_XDECREF(funcname);
  Py_XDECREF(empty_dict); 
  Py_XDECREF(empty_tuple); 
  Py_XDECREF(empty_string); 
  Py_XDECREF(empty_code);
  Py_XDECREF(code); 
  Py_XDECREF(frame); 
}
Ejemplo n.º 11
0
__declspec(dllexport) __stdcall LPXLOPER ExPyDispatch(LPXLOPER p1,
						      ...)
{
  XLOPER xCaller;
  int status;
  char formula[256];

  status=Excel4(xlfCaller,
		&xCaller,
		0); 
  XLOPER xCell;
  if ( xCaller.xltype == xltypeSRef ||   xCaller.xltype == xltypeRef )
  {
      status=Excel4(xlfGetFormula,
		  &xCell,
		  1,
		  &xCaller ); 
      size_t len=xCell.val.str[0];
      memcpy(formula, 
	     xCell.val.str+1, 
	     len);
      formula[len]=0;
  }
  else
  {
     MessageBox(GetFocus(), 
		"This function can only be called from the spreadsheet" ,  
		"Error ", 
		MB_OK | MB_ICONSTOP);
     return NULL;
  }
  

  PyObject *m = PyImport_ImportModule("ExPy");

  PyObject *PyNArgs = PyObject_GetAttrString(m, "nArgs");
  PyObject *PyNArgsRes = PyObject_CallFunction(PyNArgs, "s", formula);
  int nargs;
  if (PyArg_ParseTuple(PyNArgsRes, "i", &nargs))
  {
    // do nothing
  }
  else
  {
    printf("Could not convert");
  }

  PyObject * dispArgs=NULL;
  if (nargs>1)
  {
    char fmt[nargs];
    size_t i;
    for(i=0; i<nargs-1; ++i)
      fmt[i]='i';
    fmt[nargs-1]=0;
    va_list vl;
    va_start(vl, p1);
    dispArgs=Py_VaBuildValue(fmt, vl);
    if (dispArgs==NULL)
    {
      PyErr_Print();
    }
  }

  PyObject *PyDispatch = PyObject_GetAttrString(m, "dispatch");
  if (PyDispatch==NULL)
  {
    PyErr_Print();
    return NULL;
  }
  PyObject *PyDispRes;
  if (nargs==0)
  {
    PyDispRes  = PyObject_CallFunction(PyDispatch, "s", formula);
  }
  else if (nargs==1)
  {
    PyDispRes  = PyObject_CallFunction(PyDispatch, "si", formula, p1);
  }
  else
  {
    PyDispRes  = PyObject_CallFunction(PyDispatch, "siO", formula, p1, dispArgs);
  }

  if (PyDispRes==NULL)
  {
    PyErr_Print();
  }

  LPXLOPER res;
  if (PyArg_ParseTuple(PyDispRes, "i", &res))
  {
    // do nothing
  }
  else
  {
    PyErr_Print();
  }

  Py_XDECREF(m);
  Py_XDECREF(PyNArgs);
  if (dispArgs)
  {
    Py_XDECREF(dispArgs);
  }
  Py_XDECREF(PyDispatch);
  Py_XDECREF(PyDispRes);

  return res;
  
}
Ejemplo n.º 12
0
void CDummyClientManager::CallFunctionVa( int _startIndex, int _endIndex, acstr _funcName, CStringA _format, va_list _vaList )
{
	PyObject *module;
	CtesttoolDlg* dlg = (CtesttoolDlg*)AfxGetApp()->m_pMainWnd;
	CString logStr;
	
	std::vector<int> variableIndexArray;
	int formatLength = _format.GetLength();
	for( int i = 0; i < formatLength; i++ )
	{
		if( _format.GetAt(i) == 'v' )
		{
			variableIndexArray.push_back(i);
			_format.SetAt(i, 'i');
		}
	}

	CStringA format = "(" + _format + ")";
	int variableIndexArraySize = variableIndexArray.size();

	PyObject *parameters;
	CDummyClient *targetClient;

	for( int i = _startIndex; i <= _endIndex; i++ )
	{
		// 모듈 로드
		for( int j = 0; j < variableIndexArraySize; j++ )
		{
			int *pList = (int *)_vaList;
			pList[variableIndexArray[j]] = i;
		}

		parameters = Py_VaBuildValue( format, _vaList );

		if( i == MAINSCRIPT )
		{
			if( mainScriptmodule != NULL )
			{
				module = mainScriptmodule;
			}
			else
			{		
				dlg->addMainLog( L"[에러 - CallFunction] 메인 스크립트가 없습니다." );
				dlg->showMainLog();
				continue;
			}
		}
		else
		{
			targetClient =  GetDummyClientByIndex( i );
			if( targetClient != NULL )
			{
				module = targetClient->module;
			}
			else
			{
				CString logStr;
				logStr.Format( L"[에러 - CallFunction] %d 클라이언트가 없습니다.", i );
				dlg->addMainLog( logStr );
				dlg->showMainLog();
				continue;
			}
		}
			
		// 함수 로드
		PyGILState_STATE gilState;
		gilState = PyGILState_Ensure();

		PyObject *function = PyObject_GetAttrString(module, _funcName);

		if( function != NULL )
		{ 
			PyObject_CallObject(function, parameters );
			Py_DECREF(parameters);
			PyGILState_Release( gilState );
		}
		else
		{
			targetClient->addLog( L"[에러 - CallFunction] 함수 로드 실패." );
			PyErr_Clear();	
			PyGILState_Release( gilState );
			continue;  
		}
	}
	
}
Ejemplo n.º 13
0
void TuplesDefaultImpl::m_build(va_list ap)
{
  m_retval = Py_VaBuildValue(m_current_tuple_out()->format().c_str(), ap);
}
Ejemplo n.º 14
0
PyObject *CPythonHandler::Callback(
	HANDLER_TYPE typ,
	const char *format /* = NULL */,
	...
	)
{
	va_list va;
	PyObject *args;
	PyObject *ret = NULL;

	if (format && *format) {
		va_start(va, format);
		args = Py_VaBuildValue((char *)format, va);
		va_end(va);
	}
	else
		args = PyTuple_New(0);

	if (args == NULL)
		return NULL;

	if (!PyTuple_Check(args)) {
		PyObject *a;

		a = PyTuple_New(1);
		if (a == NULL)
			goto done;
		if (PyTuple_SET_ITEM(a, 0, args) < 0) {
			Py_DECREF(a);
			goto done;
		}
		// 'args' ref consumed by _SET_ITEM.
		args = a;
	}

	ret = DoCallback(typ, args);
	if (!ret) {
		if (m_engine->m_reload_exception &&
			PyErr_ExceptionMatches(m_engine->m_reload_exception)) {
			PyErr_Clear();
			// Need to call term first
			PyObject *temp_args = Py_BuildValue("(i)", 0);
			ret = DoCallback(HANDLER_TERM, temp_args);
			Py_XDECREF(temp_args);
			if (!ret) {
				ExtensionError(NULL, "Terminating for reload failed");
				PyErr_Clear();
			}
			Py_XDECREF(ret);
			// Now force the reload and refresh of all callbacks.
			if (!LoadHandler(true))
				goto done;
			Py_XDECREF(m_callback_init);
			m_callback_init = NULL;
			Py_XDECREF(m_callback_do);
			m_callback_do = NULL;
			Py_XDECREF(m_callback_term);
			m_callback_term = NULL;
			// call init again
			temp_args = Py_BuildValue("(z)", NULL);
			ret = DoCallback(HANDLER_INIT, temp_args);
			Py_XDECREF(temp_args);
			if (!ret) {
				ExtensionError(NULL, "Reinitializing after import failed");
				PyErr_Clear();
			}
			Py_XDECREF(ret);
			// And make the original call again.
			ret = DoCallback(typ, args);			
		}
	}
done:
	Py_DECREF(args);
	return ret;
}