/* \method socket.attachtarget \description Send a target request to this client. \param callback The full name (including the module) of a python function that will be called when the client selects a target. The function needs to have the following prototype (name may differ): <code>def callback(player, arguments, target): pass</code> - <code>player</code> The <object id="CHAR">char</object> object of the player sending the target response. - <code>arguments</code> The arguments passed to attachtarget. This is converted to a tuple. - <code>target</code> A <object id="TARGET">target</object> object representing the target. \param args A list of arguments that are passed to the callback function. This defaults to an empty list. \param cancelcallback The full name of a python function that should be called when the target is canceled. Defaults to an empty string. \param timeoutcallback The full name of a python function that should be called when the target times out. \param timeout The timeout of this target in miliseconds. Defaults to zero which means the target doesn't time out at all. */ static PyObject* wpSocket_attachtarget( wpSocket* self, PyObject* args ) { char* responsefunc; PyObject* targetargs = 0; char* cancelfunc = 0; char* timeoutfunc = 0; unsigned int timeout = 0; if ( !PyArg_ParseTuple( args, "s|O!ssI:socket.attachtarget" "(callback, [args], [cancelcallback], [timeoutcallback], [timeout])", &responsefunc, &PyList_Type, &targetargs, &cancelfunc, &timeoutfunc, &timeout ) ) { return 0; } if ( targetargs ) { targetargs = PyList_AsTuple( targetargs ); } else { targetargs = PyTuple_New( 0 ); } cPythonTarget* target = new cPythonTarget( responsefunc, timeoutfunc, cancelfunc, targetargs ); Py_DECREF(targetargs); if ( timeout ) { target->setTimeout( Server::instance()->time() + timeout ); } self->pSock->attachTarget( target ); Py_RETURN_NONE; }
/** * This method creates a Vector3Generator, given a python list object. It * uses the parsePythonTuple static methods of each of its children in * order to parse the details. * * @param args The list of parameters passed from Python. This should * be a list with a string for the head. The string * represents the type of the vector generator desired. * The tail of the list is passed to the specific generator * to be parsed further. * * @return A pointer to the newly created vector generator if everything was * created without problems. NULL, otherwise. */ VectorGenerator *VectorGenerator::parseFromPython( PyObject *args ) { BW_GUARD; // PySequence_Check( args ) // PySequence_GetItem( args, i ) // new reference PyObject *pGeneratorType = PyList_GetItem( args, 0 ); // Get the string containing the type of the VectorGenerator desired. // It should be found in the head of the arguments list. if ( ( pGeneratorType != NULL ) && PyString_Check( pGeneratorType ) ) { // Retrieve the tail of the list. The argsAsTuple object is not a // borrowed reference so it has to be deferenced. The same applies to // the tail object. PyObject *argsAsTuple = PyList_AsTuple( args ); PyObject *tail = PyTuple_GetSlice( argsAsTuple, 1, PyTuple_Size( argsAsTuple ) ); Py_DECREF( argsAsTuple ); char *generatorType = PyString_AsString( pGeneratorType ); // Based on the type of the VectorGenerator, parse the rest of the // list. The base class does not know how to do this, it only knows // what identifies a derived class - once it identifies which class // is requested, it passed the information on the the derived classes. if ( !_stricmp( generatorType, "Point" ) ) { return PointVectorGenerator::parsePythonTuple( tail ); } else if ( !_stricmp( generatorType, "Line" ) ) { return LineVectorGenerator::parsePythonTuple( tail ); } else if ( !_stricmp( generatorType, "Cylinder" ) ) { return CylinderVectorGenerator::parsePythonTuple( tail ); } else if ( !_stricmp( generatorType, "Sphere" ) ) { return SphereVectorGenerator::parsePythonTuple( tail ); } else if ( !_stricmp( generatorType, "Box" ) ) { return BoxVectorGenerator::parsePythonTuple( tail ); } else { PyErr_Format( PyExc_TypeError, "VectorGenerator: Unknown or unregistered generator %s.", generatorType ); return NULL; } } else { PyErr_SetString( PyExc_TypeError, "VectorGenerator:" "VectorGenerator name <string> required at head of list." ); return NULL; } }
static PyObject* wpSocket_attachmultitarget( wpSocket* self, PyObject* args ) { char* responsefunc; unsigned short multiid; PyObject* targetargs; char* cancelfunc = 0; char* timeoutfunc = 0; unsigned int timeout = 0; short xoffset, yoffset, zoffset; if ( !PyArg_ParseTuple( args, "sHO!hhh|ssI:socket.attachmultitarget" "(callback, multi, args, xoffset, yoffset, zoffset, [cancelcallback], [timeoutcallback], [timeout])", &responsefunc, &multiid, &PyList_Type, &targetargs, &xoffset, &yoffset, &zoffset, &cancelfunc, &timeoutfunc, &timeout ) ) { return 0; } targetargs = PyList_AsTuple( targetargs ); cPythonTarget* target = new cPythonTarget( responsefunc, timeoutfunc, cancelfunc, targetargs ); Py_DECREF(targetargs); if ( timeout ) { target->setTimeout( Server::instance()->time() + timeout ); } self->pSock->attachTarget( target, 0x4000 + multiid, xoffset, yoffset, zoffset ); Py_RETURN_NONE; }
static PyObject * parse_match(PyObject *self, PyObject *args) { const char *pattern; const char *data; PyObject *results; PyObject *mapped_results; const char *error; if (!PyArg_ParseTuple(args, "ss", &pattern, &data)) { PyErr_SetString(PyExc_TypeError, "arguments must be 2 strings"); return NULL; } results = PyList_New(0); mapped_results = PyDict_New(); error = match(pattern, data, results, mapped_results); if (error) { // TODO: what happens in the case of an exception when both objects are initialized ? // Do they leak? PyErr_SetString(PyExc_ValueError, error); return NULL; } return Py_BuildValue("(OO)", PyList_AsTuple(results), mapped_results); // TODO: would the AsTuple leak the original results ? }
/** get a tuple clone. * @throw type_err */ tuple to_tuple()const { PyObject* r = PyList_AsTuple(_p); if(r) return r; throw type_err("to_tuple failed"); }
PyObject * PySequence_Tuple(PyObject *v) { PySequenceMethods *m; if (v == NULL) return null_error(); if (PyTuple_Check(v)) { Py_INCREF(v); return v; } if (PyList_Check(v)) return PyList_AsTuple(v); /* There used to be code for strings here, but tuplifying strings is not a common activity, so I nuked it. Down with code bloat! */ /* Generic sequence object */ m = v->ob_type->tp_as_sequence; if (m && m->sq_item) { int i; PyObject *t; int n = PySequence_Size(v); if (n < 0) return NULL; t = PyTuple_New(n); if (t == NULL) return NULL; for (i = 0; ; i++) { PyObject *item = (*m->sq_item)(v, i); if (item == NULL) { if (PyErr_ExceptionMatches(PyExc_IndexError)) PyErr_Clear(); else { Py_DECREF(t); t = NULL; } break; } if (i >= n) { if (n < 500) n += 10; else n += 100; if (_PyTuple_Resize(&t, n, 0) != 0) break; } PyTuple_SET_ITEM(t, i, item); } if (i < n && t != NULL) _PyTuple_Resize(&t, i, 0); return t; } /* None of the above */ return type_error("tuple() argument must be a sequence"); }
static PyObject *c2py(std::map<K, V> const &m) { PyObject *d = PyDict_New(); for (auto &x : m) { pyref k = py_converter<K>::c2py(x.first); // if the K is a list, we transform into a tuple if (PyList_Check(k)) k = PyList_AsTuple(k); pyref v = py_converter<V>::c2py(x.second); if (PyDict_SetItem(d, k, v) == -1) { Py_DECREF(d); return NULL; } // error } return d; }
static ERL_NIF_TERM pynerl_call(ErlNifEnv* env, int arc, const ERL_NIF_TERM argv[]) { Py_Initialize(); int size; char buff[BUFF_SIZE]; PyObject *pModName, *pModule, *pFunc, *pArgs, *pArgList, *pValue; ERL_NIF_TERM eResult; pModName = pynerl_term_to_obj(env, argv[0]); pModule = PyImport_Import(pModName); Py_DECREF(pModName); if (pModule != NULL) { // TODO: error checking enif_get_string(env, argv[1], buff, BUFF_SIZE, ERL_NIF_LATIN1); pFunc = PyObject_GetAttrString(pModule, buff); if (pFunc && PyCallable_Check(pFunc)) { pArgList = pynerl_term_to_obj(env, argv[2]); pArgs = PyList_AsTuple(pArgList); Py_DECREF(pArgList); pValue = PyObject_CallObject(pFunc, pArgs); Py_DECREF(pArgs); if (pValue != NULL) { eResult = pynerl_obj_to_term(env, pValue); Py_DECREF(pValue); } else { eResult = pynerl_make_error(env, "exception", "Exception while calling function"); } Py_DECREF(pFunc); } else { eResult = pynerl_make_error(env, "nofun", "No function in module"); } Py_DECREF(pModule); } else { eResult = pynerl_make_error(env, "nomodule", "Module doesn't exist"); } Py_Finalize(); return eResult; }
PyObject* signalInstanceDisconnect(PyObject* self, PyObject* args) { PySideSignalInstance* source = reinterpret_cast<PySideSignalInstance*>(self); Shiboken::AutoDecRef pyArgs(PyList_New(0)); PyObject* slot; if (PyTuple_Check(args) && PyTuple_GET_SIZE(args)) slot = PyTuple_GET_ITEM(args, 0); else slot = Py_None; bool match = false; if (slot->ob_type == &PySideSignalInstanceType) { PySideSignalInstance* target = reinterpret_cast<PySideSignalInstance*>(slot); if (QMetaObject::checkConnectArgs(source->d->signature, target->d->signature)) { PyList_Append(pyArgs, source->d->source); Shiboken::AutoDecRef source_signature(PySide::Signal::buildQtCompatible(source->d->signature)); PyList_Append(pyArgs, source_signature); PyList_Append(pyArgs, target->d->source); Shiboken::AutoDecRef target_signature(PySide::Signal::buildQtCompatible(target->d->signature)); PyList_Append(pyArgs, target_signature); match = true; } } else { //try the first signature PyList_Append(pyArgs, source->d->source); Shiboken::AutoDecRef signature(PySide::Signal::buildQtCompatible(source->d->signature)); PyList_Append(pyArgs, signature); // disconnect all, so we need to use the c++ signature disconnect(qobj, signal, 0, 0) if (slot == Py_None) PyList_Append(pyArgs, slot); PyList_Append(pyArgs, slot); match = true; } if (match) { Shiboken::AutoDecRef tupleArgs(PyList_AsTuple(pyArgs)); Shiboken::AutoDecRef pyMethod(PyObject_GetAttrString(source->d->source, "disconnect")); PyObject* result = PyObject_CallObject(pyMethod, tupleArgs); if (result == Py_True) return result; else Py_DECREF(result); } PyErr_Format(PyExc_RuntimeError, "Failed to disconnect signal %s.", source->d->signature); return 0; }
static range* _python_function(range_request* rr, const char* funcname, const range** r) { range* result = range_new(rr); PyObject * pLibcrangeCallFunc; PyObject * pNodesReturned; PyObject * pMain = PyImport_AddModule("__main__"); // printf("rr: %p, funcname=%s, range**r = %p\n", rr, funcname, r); pLibcrangeCallFunc = PyObject_GetAttrString(pMain, "libcrange_call_func"); if (pLibcrangeCallFunc && PyCallable_Check(pLibcrangeCallFunc)) { PyObject * pRangeFuncName; PyObject * item; pRangeFuncName = PyString_FromString(funcname); PyObject * pFuncArgs; PyObject * pTempArgList = PyList_New(0); PyList_Append(pTempArgList, pRangeFuncName); Py_DECREF(pRangeFuncName); // build our range** into python function args const range** p_r = r; while (*p_r) { item = range_to_py_array(range_request_pool(rr), *p_r); PyList_Append(pTempArgList, item); Py_DECREF(item); p_r++; } pFuncArgs = PyList_AsTuple(pTempArgList); Py_DECREF(pTempArgList); // call the function pNodesReturned = PyObject_CallObject(pLibcrangeCallFunc, pFuncArgs); Py_DECREF(pFuncArgs); PyObject *iterator = PyObject_GetIter(pNodesReturned); if (iterator == NULL) { printf("ERROR: python function %s ran, but didn't return an iteratable object", funcname); return result; } // an iteratable object was returned, transform it into result while (item = PyIter_Next(iterator)) { // PyObject_Print(item, stdout, 0 ); range_add(result, PyString_AsString(item)); Py_DECREF(item); } Py_DECREF(pNodesReturned); } return result; }
/* Implementation of gdb.inferiors () -> (gdb.Inferior, ...). Returns a tuple of all inferiors. */ PyObject * gdbpy_inferiors (PyObject *unused, PyObject *unused2) { int i = 0; PyObject *list, *inferior; struct inferior *inf; list = PyList_New (0); if (!list) return NULL; iterate_over_inferiors (build_inferior_list, list); return PyList_AsTuple (list); }
PyObject* signalInstanceEmit(PyObject* self, PyObject* args) { PySideSignalInstance* source = reinterpret_cast<PySideSignalInstance*>(self); Shiboken::AutoDecRef pyArgs(PyList_New(0)); Shiboken::AutoDecRef sourceSignature(PySide::Signal::buildQtCompatible(source->d->signature)); PyList_Append(pyArgs, sourceSignature); for (Py_ssize_t i = 0, max = PyTuple_Size(args); i < max; i++) PyList_Append(pyArgs, PyTuple_GetItem(args, i)); Shiboken::AutoDecRef pyMethod(PyObject_GetAttrString(source->d->source, "emit")); Shiboken::AutoDecRef tupleArgs(PyList_AsTuple(pyArgs)); return PyObject_CallObject(pyMethod, tupleArgs); }
/* Enables list and tuple as arguments */ static void py_asargs(lua_State *L) { py_object *pobj = get_py_object(L, lua_getparam(L, 1)); if (PyObject_IsListInstance(pobj->object)) { PyObject *obj = PyList_AsTuple(pobj->object); pobj = py_object_container(L, obj, true); pobj->isargs = true; lua_pushusertag(L, pobj, python_api_tag(L)); } else if (PyObject_IsTupleInstance(pobj->object)) { Py_INCREF(pobj->object); pobj = py_object_container(L, pobj->object, true); pobj->isargs = true; lua_pushusertag(L, pobj, python_api_tag(L)); } else { luaL_argerror(L, 1, "tuple or list expected"); } }
gboolean pygts_vertex_check(PyObject* o) { gboolean check = FALSE; guint i,N; PyObject *obj; /* Check for a Vertex */ if( PyObject_TypeCheck(o, &PygtsVertexType) ) { check = TRUE; } /* Convert list into tuple */ if(PyList_Check(o)) { o = PyList_AsTuple(o); } else { Py_INCREF(o); } /* Check for a tuple of floats */ if( PyTuple_Check(o) ) { if( (N = PyTuple_Size(o)) <= 3 ) { check = TRUE; for(i=0;i<N;i++) { obj = PyTuple_GET_ITEM(o,i); if(!PyFloat_Check(obj) && !PyLong_Check(obj)) { check = FALSE; } } } } Py_DECREF(o); if( !check ) { return FALSE; } else { #if PYGTS_DEBUG if( PyObject_TypeCheck(o, &PygtsVertexType) ) { return pygts_vertex_is_ok(PYGTS_VERTEX(o)); } #endif return TRUE; } }
int runpython(const char *modname, const char * clsname, const char * funcname, const int paramhandle) { PyObject *modstr, *mod, *clsstr, *cls, *funcstr, *func, *plist, *args, *retval; /* convert module, class and func to utf-8 */ modstr = strLenToUtfPy((char *)modname, strlen(modname)); plist = getObjectFromHandle(paramhandle); /* parameters */ if (!PyList_Check(plist)) return newHandle(PyString_FromString("Error: parameters must be a list.")); /* import modules */ mod = PyImport_Import(modstr); if (mod == NULL) { Py_DECREF(modstr); return newHandle(PyString_FromString("Error: module not found.")); } if (clsname != NULL) clsstr = strLenToUtfPy((char *)clsname, strlen(clsname)); funcstr = strLenToUtfPy((char *)funcname, strlen(funcname)); if (clsname != NULL && strlen(clsname) > 0) { cls = PyObject_GetAttr(mod, clsstr); if (cls != NULL) func = PyObject_GetAttr(cls, funcstr); } else { func = PyObject_GetAttr(mod, funcstr); } if (!func || !PyCallable_Check(func)) { Py_XDECREF(cls); Py_XDECREF(mod); return newHandle(PyString_FromString("Error: function not found.")); } args = PyList_AsTuple(plist); retval = PyObject_CallObject(func, args); Py_XDECREF(args); Py_XDECREF(func); Py_XDECREF(funcstr); Py_XDECREF(cls); Py_XDECREF(clsstr); Py_XDECREF(mod); Py_XDECREF(modstr); /* keep the return value */ return newHandle(retval); }
void test_PythonAPI() { double a_ = 3.4; PyObject* a = PyFloat_FromDouble(a_); PyObject* b = PyFloat_FromDouble(7); PyObject* c = PyNumber_Add(a, b); PyObject* list = PyList_New(0); PyList_Append(list, a); PyList_Append(list, c); PyList_Append(list, b); PyObject* tp = PyList_AsTuple(list); int tp_len = PySequence_Length(tp); for (int i=0; i<tp_len; i++) { PyObject* qp = PySequence_GetItem(tp, i); double q = PyFloat_AS_DOUBLE(qp); std::cout << "tp[" << i << "]=" << q << " "; } std::cout << std::endl; }
/* Implementation of gdb.inferiors () -> (gdb.Inferior, ...). Returns a tuple of all inferiors. */ PyObject * gdbpy_inferiors (PyObject *unused, PyObject *unused2) { PyObject *list, *tuple; list = PyList_New (0); if (!list) return NULL; if (iterate_over_inferiors (build_inferior_list, list)) { Py_DECREF (list); return NULL; } tuple = PyList_AsTuple (list); Py_DECREF (list); return tuple; }
/* * Adds a temp effect to this multi. */ static PyObject* wpMulti_addtimer( wpMulti* self, PyObject* args ) { if( (PyTuple_Size( args ) < 3 && PyTuple_Size( args ) > 4) || !checkArgInt( 0 ) || !checkArgStr( 1 ) || !PyList_Check( PyTuple_GetItem( args, 2 ) ) ) { PyErr_BadArgument(); return NULL; } UINT32 expiretime = getArgInt( 0 ); QString function = getArgStr( 1 ); PyObject *py_args = PyList_AsTuple( PyTuple_GetItem( args, 2 ) ); cPythonEffect *effect = new cPythonEffect( function, py_args ); if( checkArgInt( 3 ) && getArgInt( 3 ) != 0 ) effect->setSerializable( true ); else effect->setSerializable( false ); effect->setDest( self->pMulti->serial() ); effect->setExpiretime_ms( expiretime ); TempEffects::instance()->insert( effect ); return PyTrue; }
/* * Return 0 if successful */ static int _PyArray_DescrHashImp(PyArray_Descr *descr, npy_hash_t *hash) { PyObject *l, *tl; int st; l = PyList_New(0); if (l == NULL) { return -1; } st = _array_descr_walk(descr, l); if (st) { Py_DECREF(l); return -1; } /* * Convert the list to tuple and compute the tuple hash using python * builtin function */ tl = PyList_AsTuple(l); Py_DECREF(l); if (tl == NULL) return -1; *hash = PyObject_Hash(tl); Py_DECREF(tl); if (*hash == -1) { /* XXX: does PyObject_Hash set an exception on failure ? */ #if 0 PyErr_SetString(PyExc_SystemError, "(Hash) Error while hashing final tuple"); #endif return -1; } return 0; }
void wxPyCoreModuleInject(PyObject* moduleDict) { // Create an exception object to use for wxASSERTions wxAssertionError = PyErr_NewException("wx._core.wxAssertionError", PyExc_AssertionError, NULL); PyDict_SetItemString(moduleDict, "wxAssertionError", wxAssertionError); // An alias that should be deprecated sometime PyDict_SetItemString(moduleDict, "PyAssertionError", wxAssertionError); // // Create an exception object to use when the app object hasn't been created yet // wxPyNoAppError = PyErr_NewException("wx._core.PyNoAppError", // PyExc_RuntimeError, NULL); // PyDict_SetItemString(moduleDict, "PyNoAppError", wxPyNoAppError); #ifdef __WXGTK__ #define wxPort "__WXGTK__" #define wxPortName "wxGTK" #endif #ifdef __WXMSW__ #define wxPort "__WXMSW__" #define wxPortName "wxMSW" #endif #ifdef __WXMAC__ #define wxPort "__WXMAC__" #define wxPortName "wxMac" #endif wxInitAllImageHandlers(); // TODO: Find some blackmagic way to deprecate wx.Platform such that it raises // a wraning when used... Maybe a class that returns wx.Port for any __getattr__? PyDict_SetItemString(moduleDict, "Port", PyUnicode_FromString(wxPort)); PyDict_SetItemString(moduleDict, "Platform", PyUnicode_FromString(wxPort)); // Make a tuple of strings that gives more info about the platform and build. PyObject* PlatformInfo = PyList_New(0); PyObject* obj; #define _AddInfoString(st) \ obj = PyUnicode_FromString(st); \ PyList_Append(PlatformInfo, obj); \ Py_DECREF(obj) _AddInfoString(wxPort); _AddInfoString(wxPortName); #if wxUSE_UNICODE _AddInfoString("unicode"); #if wxUSE_UNICODE_WCHAR _AddInfoString("unicode-wchar"); #else _AddInfoString("unicode-utf8"); #endif #else _AddInfoString("ansi"); #endif #ifdef __WXOSX__ _AddInfoString("wxOSX"); #endif #ifdef __WXOSX_CARBON__ _AddInfoString("wxOSX-carbon"); #endif #ifdef __WXOSX_COCOA__ _AddInfoString("wxOSX-cocoa"); #endif #ifdef __WXGTK__ #ifdef __WXGTK3__ _AddInfoString("gtk3"); #elif __WXGTK20__ _AddInfoString("gtk2"); #else _AddInfoString("gtk1"); #endif #endif #ifdef __WXDEBUG__ _AddInfoString("wx-assertions-on"); #else _AddInfoString("wx-assertions-off"); #endif _AddInfoString("phoenix"); #undef _AddInfoString PyObject* PlatformInfoTuple = PyList_AsTuple(PlatformInfo); Py_DECREF(PlatformInfo); PyDict_SetItemString(moduleDict, "PlatformInfo", PlatformInfoTuple); }
static PyObject * struct_unpack(PyObject *self, PyObject *args) { const formatdef *f, *e; char *str, *start, *fmt, *s; char c; int len, size, num; PyObject *res, *v; if (!PyArg_ParseTuple(args, "ss#:unpack", &fmt, &start, &len)) return NULL; f = whichtable(&fmt); size = calcsize(fmt, f); if (size < 0) return NULL; if (size != len) { PyErr_SetString(StructError, "unpack str size does not match format"); return NULL; } res = PyList_New(0); if (res == NULL) return NULL; str = start; s = fmt; while ((c = *s++) != '\0') { if (isspace(Py_CHARMASK(c))) continue; if ('0' <= c && c <= '9') { num = c - '0'; while ('0' <= (c = *s++) && c <= '9') num = num*10 + (c - '0'); if (c == '\0') break; } else num = 1; e = getentry(c, f); if (e == NULL) goto fail; str = start + align((int)(str-start), c, e); if (num == 0 && c != 's') continue; do { if (c == 'x') { str += num; break; } if (c == 's') { /* num is string size, not repeat count */ v = PyString_FromStringAndSize(str, num); if (v == NULL) goto fail; str += num; num = 0; } else if (c == 'p') { /* num is string buffer size, not repeat count */ int n = *(unsigned char*)str; /* first byte (unsigned) is string size */ if (n >= num) n = num-1; v = PyString_FromStringAndSize(str+1, n); if (v == NULL) goto fail; str += num; num = 0; } else { v = e->unpack(str, e); if (v == NULL) goto fail; str += e->size; } if (v == NULL || PyList_Append(res, v) < 0) goto fail; Py_DECREF(v); } while (--num > 0); } v = PyList_AsTuple(res); Py_DECREF(res); return v; fail: Py_DECREF(res); return NULL; }
// DEPRECATED (??? - Couldnt find the new method and all scripts still using this) static PyObject* wpSocket_sendgump( wpSocket* self, PyObject* args ) { // Parameters: // x, y, nomove, noclose, nodispose, serial, type, layout, text, callback, args int x, y; bool nomove, noclose, nodispose; unsigned int serial, type; PyObject* layout; PyObject* texts; PyObject* py_args; PyObject* callback = 0; if ( !PyArg_ParseTuple( args, "iiBBBIIO!O!OO!:socket.sendgump", &x, &y, &nomove, &noclose, &nodispose, &serial, &type, &PyList_Type, &layout, &PyList_Type, &texts, &callback, &PyList_Type, &py_args ) ) { return 0; } // Comment: Couldnt find the new method and all scripts still using this // PyErr_Format( PyExc_DeprecationWarning, "socket.sendgump is deprecated, please use cGump class instead" ); PythonFunction* toCall = 0; if ( callback ) { if ( !PyCallable_Check( callback ) ) { QString func = boost::python::extract<QString>( callback ); if ( func.isNull() ) { PyErr_SetString( PyExc_TypeError, "Bad argument on socket.sendgump callback type" ); return 0; } Console::instance()->log( LOG_WARNING, tr("Using deprecated string as callback identifier [%1]").arg(func) ); toCall = new PythonFunction( func ); // This is optional, if we used the empty string, treat as it was a None object if ( !func.isEmpty() && ( !toCall || !toCall->isValid() ) ) { PyErr_Format(PyExc_RuntimeError, "The function callback you specified was invalid: %s", func.toLatin1().constData()); return 0; } } else toCall = new PythonFunction( callback ); } // Convert py_args to a tuple py_args = PyList_AsTuple( py_args ); cPythonGump* gump = new cPythonGump( toCall, py_args ); Py_DECREF(py_args); if ( serial ) gump->setSerial( serial ); if ( type ) gump->setType( type ); gump->setX( x ); gump->setY( y ); gump->setNoClose( noclose ); gump->setNoMove( nomove ); gump->setNoDispose( nodispose ); qint32 i; for ( i = 0; i < PyList_Size( layout ); ++i ) { PyObject* item = PyList_GetItem( layout, i ); if ( PyUnicode_Check( item ) || PyString_Check( item ) ) { gump->addRawLayout( boost::python::extract<QString>( item ) ); } else { gump->addRawLayout( "" ); } } for ( i = 0; i < PyList_Size( texts ); ++i ) { PyObject* item = PyList_GetItem( texts, i ); if ( PyUnicode_Check( item ) || PyString_Check( item ) ) { gump->addRawText( boost::python::extract<QString>( item ) ); } else { gump->addRawText( "" ); } } self->pSock->send( gump ); return PyInt_FromLong( gump->serial() ); }
PyObject * captureObject_next(captureObject *self) { u_char *packet = NULL; struct pcap_pkthdr header; PyObject *ethernet = NULL; PyObject *result = NULL; PyObject *resultTuple = NULL; ethernet_t *eth_header = NULL; char buffer[255]; double packetTime; int packet_offset = 0; PyObject *remaining = NULL; int offset[5] = { 0, 0, 0, 0, 0 }; packet = (u_char *) pcap_next(self->pcap, &header); if (! packet) { Py_INCREF(Py_None); return Py_None; // PyErr_SetString(ErrorObject, "No data available before timeout"); // return NULL; } sprintf(buffer, "%ld.%ld", (long) header.ts.tv_sec, (long) header.ts.tv_usec); packetTime = strtod(buffer, NULL); result = PyList_New(0); switch (pcap_datalink(self->pcap)) { case DLT_EN10MB: { eth_header = (ethernet_t *) packet; ethernet = (PyObject *) PyProtocol_newEthernetObjectFromPacket(eth_header, &packet_offset); offset[0] = packet_offset; PyList_Append(result, ethernet); Py_DECREF(ethernet); switch (ntohs(eth_header->ether_type)) { case ETHERTYPE_IP: { if (! parseIP(result, header, packet, &packet_offset)) { Py_DECREF(result); return NULL; } offset[1] = packet_offset; break; } case ETHERTYPE_ARP: if (! parseARP(result, header, packet, &packet_offset)) { Py_DECREF(result); return NULL; } offset[2] = packet_offset; break; default: { } } break; } case DLT_NULL: { packet_offset = 4; if (! parseIP(result, header, packet, &packet_offset)) { Py_DECREF(result); return NULL; } offset[3] = packet_offset; break; } } if ((int) (header.len) - packet_offset < 0) { Py_DECREF(result); PyErr_Format(ErrorObject, "Parsed parsed end of packet (%d %d %d %d)", offset[0], offset[1], offset[2], offset[3]); return NULL; } remaining = PyString_FromStringAndSize((char *) (packet + packet_offset), header.len - packet_offset); PyList_Append(result, remaining); Py_DECREF(remaining); PyList_Append(result, PyFloat_FromDouble(packetTime)); resultTuple = PyList_AsTuple(result); Py_DECREF(result); return resultTuple; }
static PyObject* wpSocket_attachitemtarget( wpSocket* self, PyObject* args ) { char* responsefunc; PyObject* items; PyObject* targetargs = 0; char* cancelfunc = 0; char* timeoutfunc = 0; unsigned int timeout = 0; int xoffset, yoffset, zoffset; if ( !PyArg_ParseTuple( args, "sO!iii|O!ssI:socket.attachitemtarget" "(callback, [items], [args], [cancelcallback], [timeoutcallback], [timeout])", &responsefunc, &PyList_Type, &items, &xoffset, &yoffset, &zoffset, &PyList_Type, &targetargs, &cancelfunc, &timeoutfunc, &timeout ) ) { return 0; } if ( targetargs ) { targetargs = PyList_AsTuple( targetargs ); } else { targetargs = PyTuple_New( 0 ); } std::vector<stTargetItem> targetitems; // Evaluate the given items for ( int i = 0; i < PyList_Size( items ); ++i ) { PyObject* listitem = PyList_GetItem( items, i ); // Has to be another list if ( PyList_Check( listitem ) ) { // id, xoffset, yoffset, zoffset, hue if ( PyList_Size( listitem ) == 5 ) { PyObject* id = PyList_GetItem( listitem, 0 ); PyObject* ixoffset = PyList_GetItem( listitem, 1 ); PyObject* iyoffset = PyList_GetItem( listitem, 2 ); PyObject* izoffset = PyList_GetItem( listitem, 3 ); PyObject* hue = PyList_GetItem( listitem, 4 ); if ( PyInt_Check( id ) && PyInt_Check( ixoffset ) && PyInt_Check( iyoffset ) && PyInt_Check( izoffset ) && PyInt_Check( hue ) ) { stTargetItem targetitem; targetitem.id = PyInt_AsLong( id ); targetitem.xOffset = PyInt_AsLong( ixoffset ); targetitem.yOffset = PyInt_AsLong( iyoffset ); targetitem.zOffset = PyInt_AsLong( izoffset ); targetitem.hue = PyInt_AsLong( hue ); targetitems.push_back( targetitem ); } } } } cPythonTarget* target = new cPythonTarget( responsefunc, timeoutfunc, cancelfunc, targetargs ); if ( timeout ) { target->setTimeout( Server::instance()->time() + timeout ); } self->pSock->attachTarget( target, targetitems, xoffset, yoffset, zoffset ); Py_DECREF(targetargs); Py_RETURN_NONE; }
int runpython_ts(const char *modname, const char * clsname, const char * funcname, const int paramhandle) { PyObject *modstr, *mod, *clsstr, *cls, *funcstr, *func, *plist, *args, *retval; /* convert module, class and func to utf-8 */ modstr = strLenToUtfPy((char *)modname, strlen(modname)); plist = getObjectFromHandle(paramhandle); /* parameters */ if (PyString_Check(plist)) { /* parameter should be a json string */ plist = from_json(plist); if (plist == NULL) { error_msg("Error in json parameter string"); return -1; } } if (!PyList_Check(plist)) { error_msg("Error in runpython: parameters must be a list"); return -1; } /* import modules */ mod = PyImport_Import(modstr); if (mod == NULL) { Py_DECREF(modstr); error_msg("Error in runpython: Module not found"); return -1; } if (clsname != NULL) clsstr = strLenToUtfPy((char *)clsname, strlen(clsname)); funcstr = strLenToUtfPy((char *)funcname, strlen(funcname)); if (clsname != NULL && strlen(clsname) > 0) { cls = PyObject_GetAttr(mod, clsstr); if (cls != NULL) func = PyObject_GetAttr(cls, funcstr); } else { func = PyObject_GetAttr(mod, funcstr); } if (!func || !PyCallable_Check(func)) { Py_XDECREF(cls); Py_XDECREF(mod); error_msg("Error in runpython: Function not found"); return -1; } args = PyList_AsTuple(plist); retval = PyObject_CallObject(func, args); Py_XDECREF(args); Py_XDECREF(func); Py_XDECREF(funcstr); Py_XDECREF(cls); Py_XDECREF(clsstr); Py_XDECREF(mod); Py_XDECREF(modstr); if (!retval) { PyErr_Print(); error_msg("Error in runpython: See QPRINT for details"); return -1; } /* keep the return value */ return newHandle(retval); }
/* {{{ pip_hash_to_tuple(zval **hash) Convert a PHP hash to a Python tuple */ PyObject * pip_hash_to_tuple(zval **hash) { return PyList_AsTuple(pip_hash_to_list(hash)); }
static PyObject *py_tag(PyObject *self, PyObject *args) { PyObject *seq; int buf_len; const char *buf; if (!PyArg_ParseTuple(args, "y#O", &buf, &buf_len, &seq)) return NULL; if (buf_len & (buf_len-1)) { PyErr_SetString(PyExc_ValueError, "Weights vector length must be power of 2"); return NULL; } int clear_seq = 0; if (PyList_Check(seq)) { seq = PyList_AsTuple(seq); clear_seq = 1; } else if (!PyTuple_Check(seq)) { PyErr_SetString(PyExc_TypeError, "Expected a list or tuple"); return NULL; } const real *weights = (real*)buf; size_t weights_len = buf_len / sizeof(*weights); Py_ssize_t seq_len = PyTuple_Size(seq), i, j; uint8_t *field_buf[seq_len*N_TAG_FIELDS]; size_t field_len[seq_len*N_TAG_FIELDS]; PyObject *field_bytes[seq_len*N_TAG_FIELDS]; for (i=0; i<seq_len; i++) { PyObject *row = PyTuple_GetItem(seq, i); if (PyUnicode_Check(row)) { if (N_TAG_FIELDS != 1) { char msg[0x100]; snprintf(msg, sizeof(msg), "Expected %d fields for token, found single string", N_TAG_FIELDS); PyErr_SetString(PyExc_ValueError, msg); return NULL; } PyObject *buf = PyUnicode_AsEncodedString(row, "utf-8", NULL); field_buf[i*N_TAG_FIELDS + 0] = (uint8_t*)PyBytes_AsString(buf); field_len[i*N_TAG_FIELDS + 0] = PyBytes_Size(buf); field_bytes[i*N_TAG_FIELDS + 0] = buf; } else { int clear_row = 0; if (PyList_Check(row)) { row = PyList_AsTuple(row); clear_row = 1; } if (!PyTuple_Check(row)) { PyErr_SetString(PyExc_TypeError, "Expected tuple, list or str for token"); return NULL; } if (PyTuple_Size(row) != N_TAG_FIELDS) { char msg[0x100]; snprintf(msg, sizeof(msg), "Expected %d fields for token, found %zd", N_TAG_FIELDS, PyTuple_Size(row)); PyErr_SetString(PyExc_ValueError, msg); return NULL; } for (j=0; j<N_TAG_FIELDS; j++) { PyObject *str = PyTuple_GetItem(row, j); if (PyBytes_Check(str)) { field_buf[i*N_TAG_FIELDS + j] = (uint8_t*)PyBytes_AsString(str); field_len[i*N_TAG_FIELDS + j] = PyBytes_Size(str); field_bytes[i*N_TAG_FIELDS + j] = NULL; } else if(PyUnicode_Check(str)) { PyObject *buf = PyUnicode_AsEncodedString( str, "utf-8", NULL); field_buf[i*N_TAG_FIELDS + j] = (uint8_t*)PyBytes_AsString(buf); field_len[i*N_TAG_FIELDS + j] = PyBytes_Size(buf); field_bytes[i*N_TAG_FIELDS + j] = buf; } else { PyErr_SetString(PyExc_TypeError, "Expected bytes or str"); return NULL; } } if (clear_row) Py_CLEAR(row); } } label result[seq_len]; beam_search( (const uint8_t**)field_buf, field_len, N_TAG_FIELDS, seq_len, weights, weights_len, 1, result); PyObject *tags = PyTuple_New(seq_len); for (i=0; i<seq_len; i++) PyTuple_SetItem(tags, i, PyUnicode_FromString(tag_str[result[i]])); for (i=0; i<seq_len; i++) { for (j=0; j<N_TAG_FIELDS; j++) { Py_CLEAR(field_bytes[i*N_TAG_FIELDS + j]); } } if (clear_seq) Py_CLEAR(seq); return tags; }
//! CSL method: call(app, model, method, (arg0, arg1, ...)) static PyObject * c_call(PyObject *self, PyObject *args) { /*! * This method can be used in CSL scripts to call Comar methods * internally. * * @return Called method's reply */ PyObject *ret, *tuple = NULL; char *app, *model, *method, *interface, *path; int size, i; if (!PyArg_ParseTuple(args, "sss|O", &app, &model, &method, &tuple)) return NULL; if (!tuple) { tuple = PyTuple_New(0); } DBusConnection *conn; DBusError err; DBusMessage *msg, *reply; DBusMessageIter iter; dbus_error_init(&err); conn = dbus_bus_get_private(DBUS_BUS_SYSTEM, &err); if (dbus_error_is_set(&err)) { PyErr_SetString(PyExc_Exception, "Unable to open connection for call() method."); dbus_error_free(&err); return NULL; } size = strlen(cfg_bus_interface) + 1 + strlen(model) + 1; interface = malloc(size); snprintf(interface, size, "%s.%s", cfg_bus_interface, model); interface[size - 1] = '\0'; size = strlen("/package/") + strlen(app) + 1; path = malloc(size); snprintf(path, size, "/package/%s", app); path[size - 1] = '\0'; msg = dbus_message_new_method_call(cfg_bus_name, path, interface, method); free(interface); free(path); dbus_message_iter_init_append(msg, &iter); if (PyTuple_Check(tuple)) { if (PyTuple_Size(tuple) > 0) { for (i = 0; i < PyTuple_Size(tuple); i++) { if (dbus_py_export(&iter, PyTuple_GetItem(tuple, i)) != 0) { return NULL; } } } } else { if (dbus_py_export(&iter, tuple) != 0) { return NULL; } } reply = dbus_connection_send_with_reply_and_block(conn, msg, -1, &err); dbus_message_unref(msg); dbus_connection_close(conn); dbus_connection_unref(conn); if (dbus_error_is_set(&err)) { PyErr_Format(PyExc_Exception, "Unable to call method: %s", err.message); dbus_error_free(&err); return NULL; } switch (dbus_message_get_type(reply)) { case DBUS_MESSAGE_TYPE_METHOD_RETURN: ret = PyList_AsTuple(dbus_py_import(reply)); if (PyTuple_Size(ret) == 1) { ret = PyTuple_GetItem(ret, 0); } dbus_message_unref(reply); return ret; case DBUS_MESSAGE_TYPE_ERROR: PyErr_SetString(PyExc_Exception, dbus_message_get_error_name(reply)); dbus_message_unref(reply); return NULL; } Py_INCREF(Py_None); return Py_None; }
Charm_t *CallMethod(Charm_t *pObject, const char *func_name, char *types, ...) { PyObject *pFunc, *pValue, *pArgs, *o = NULL, *l = NULL; char *fmt, *list, *list2, *token, *token2; char delims[] = "[,]"; va_list arg_list; if(pObject == NULL) return NULL; /* can't do anything for you */ pArgs = PyList_New(0); va_start(arg_list, types); /* iterate through string one character at a time */ for(fmt = types; *fmt != '\0'; fmt++) { if(*fmt != '%') continue; switch(*++fmt) { case 's': o = PyUnicode_FromString(va_arg(arg_list, char *)); PyList_Append(pArgs, o); Free(o); break; case 'I': o = PyLong_FromLong(atoi(va_arg(arg_list, char *))); PyList_Append(pArgs, o); Free(o); break; case 'i': o = PyLong_FromLong((long) va_arg(arg_list, int *)); PyList_Append(pArgs, o); Free(o); break; case 'A': // list of strings? list = va_arg(arg_list, char *); // printf("attrlist ptr: '%s'\n", list); list2 = strdup(list); token = strtok(list2, delims); token2 = trim(token); o = PyList_New(0); while(token2 != NULL) { //printf("Adding : '%s'\n", token2); l = PyUnicode_FromString(token2); PyList_Append(o, l); Py_XDECREF(l); token = strtok(NULL, delims); token2 = trim(token); } PyList_Append(pArgs, o); Free(o); free(list2); break; case 'O': o = va_arg(arg_list, PyObject *); PyList_Append(pArgs, o); Free(o); break; default: break; } } va_end(arg_list); /* fetch the attribtue from the object context - function in this case */ pFunc = PyObject_GetAttrString(pObject, func_name); /* pFunc is a new reference */ if (pFunc && PyCallable_Check(pFunc)) { /* call the function and pass the tuple since ar*/ pValue = PyObject_CallObject(pFunc, PyList_AsTuple(pArgs)); if(pValue == NULL) { if (PyErr_Occurred()) PyErr_Print(); } Free(pFunc); Free(pArgs); return (Charm_t *) pValue; } return NULL; }
/* {{{ convert_hash_to_tuple(zval **hash) Convert a PHP hash to a Python tuple */ static PyObject * convert_hash_to_tuple(zval **hash) { return PyList_AsTuple(convert_hash_to_list(hash)); }